简体   繁体   中英

Measuring time with time.h?

I'm trying to measure time it takes to run a command using my own command interpreter, but is the time correct? When I run a command it says time much longer than expected:

miniShell>> pwd
/home/dac/.clion11/system/cmake/generated/c0a6fa89/c0a6fa89/Debug
Execution time 1828 ms

I'm using the gettimeofday as can be seen from the code. Isn't it wrong somewhere and should be changed so that the timing looks reasonable?

If I make a minimal example, then it looks and runs like this:

#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>

int main(int argc, char *argv[]) {
    long time;
    struct timeval time_start;
    struct timeval time_end;
    gettimeofday(&time_start, NULL);
    printf("run program>> ");
    gettimeofday(&time_end, NULL);
    time = (time_end.tv_sec-time_start.tv_sec)*1000000 + time_end.tv_usec-time_start.tv_usec;
    printf("Execution time %ld ms\n", time);    /*Print out the execution time*/
    return (0);
}

Then I run it

  /home/dac/.clion11/system/cmake/generated/c0a6fa89/c0a6fa89/Debug/oslab
    run program>> Execution time 14 ms

    Process finished with exit code 0

The above 14 ms seems reasonable, why is the time so long for my command?

struct timeval 中的 tv_usec 是以微秒为单位的时间,而不是毫秒。

You compute the time incorrectly. tv_usec , where the u stands for the Greek lowercase letter μ ("mu"), holds a number of microseconds. Fix the formula this way:

    gettimeofday(&time_end, NULL);
    time = (((time_end.tv_sec - time_start.tv_sec) * 1000000LL) +
            time_end.tv_usec - time_start.tv_usec) / 1000;
    printf("Execution time %ld ms\n", time);    /* Print out the execution time*/

It is preferable to make the computation in 64 bits to avoid overflows if long is 32 bits and the elapsed time can exceed 40 minutes.

If you want to preserve the maximum precision, keep the computation in microseconds and print the number of milliseconds with a decimal point:

    gettimeofday(&time_end, NULL);
    time = (time_end.tv_sec - time_start.tv_sec) * 1000000 +
            time_end.tv_usec - time_start.tv_usec;
    printf("Execution time %ld.%03ld ms\n", time / 1000, time % 1000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM