测量程序的执行时间

Measuring execution time of a program

link here 表示 gettimeofday() 设置了一个结构,其中包含自 Epoch 以来的秒数和微秒数(请告诉我 Epoch 是什么)。考虑到这一点,我在使用参数 3 调用睡眠函数之前和之后设置了一个结构。因此这些结构的总时差设置为 3 秒或 3000000 微秒,但它似乎给出了一些错误的输出。我哪里错了?

#include<iostream>
#include<ctime>
#include<unistd.h>
#include<cstdio>
#include<sys/time.h>

using namespace std;

int main()
{
    struct timeval start,end;
    gettimeofday(&start,NULL);
    sleep(3);
    gettimeofday(&end,NULL);
    cout<<start.tv_usec<<endl;
    cout<<end.tv_usec<<endl;
    cout<<end.tv_usec-start.tv_usec;
    return 0;
}

这是你遗漏的要点:

unsigned long time_in_micros = 1000000 * tv_sec + tv_usec;

要获得以微秒为单位的经过时间,您需要ADD "seconds" 到"microseconds"。您不能只忽略 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() 链接: