测量程序的执行时间

时间:2016-03-27 05:33:09

标签: profiling execution-time

链接here表示../../folder/file设置的结构包含自 Epoch 以来的秒数和微秒数(请告诉我Epoch是什么)。考虑到这一点,我在使用参数3调用sleep函数之前和之后设置了一个结构。所以这些结构的总时间差设置是3秒或3000000微秒,但它似乎给出了一些错误的输出。我哪里出错?

gettimeofday()

1 个答案:

答案 0 :(得分:2)

以下是您遗漏的一点:

unsigned long time_in_micros = 1000000 * tv_sec + tv_usec;

要以微秒为单位获取经过的时间,您需要 ADD “秒”到“微秒”。你不能只是忽略 tv_sec字段!

示例代码:

#include <unistd.h>
#include <stdio.h>
#include <time.h>
#include <sys/time.h>

int main(int argc, char *argv[])
{
    struct timeval start,end;
    gettimeofday(&start,NULL);
    sleep(3);
    gettimeofday(&end,NULL);
    printf ("start: %ld:%ld\n", start.tv_sec, start.tv_usec);
    printf ("end:   %ld:%ld\n", end.tv_sec, end.tv_usec);
    printf ("diff:  %ld:%ld\n",
      end.tv_sec-start.tv_sec, end.tv_usec-start.tv_usec);

    gettimeofday(&start,NULL);
    sleep(10);
    gettimeofday(&end,NULL);
    printf ("start: %ld:%ld\n", start.tv_sec, start.tv_usec);
    printf ("end:   %ld:%ld\n", end.tv_sec, end.tv_usec);
    printf ("diff:  %ld:%ld\n", 
      end.tv_sec-start.tv_sec, end.tv_usec-start.tv_usec);
    return 0;
}

对应输出:

start: 1459100430:214715
end:   1459100433:215357
diff:  3:642
start: 1459100433:215394
end:   1459100443:217024
diff:  10:1630

gettimeofday()链接: