如何在C ++中测量挂钟时间而不是cpu时间?

时间:2019-05-31 18:25:05

标签: c++ time

我想测量我的算法在C ++中占用的挂钟时间。许多文章都指向此代码。

clock_t begin_time, end_time;
begin_time = clock();
Algorithm();
end_time = clock();
cout << ((double)(end_time - begin_time)/CLOCKS_PER_SEC) << endl;

但是,这只能衡量我的算法占用的CPU时间。 其他文章指出了此代码。

double getUnixTime(void)
{
    struct timespec tv;

    if(clock_gettime(CLOCK_REALTIME, &tv) != 0) return 0;

    return (tv.tv_sec + (tv.tv_nsec / 1000000000.0));
}
double begin_time, end_time;
begin_time = getUnixTime();
Algorithm();
end_time = getUnixTime();
cout << (double) (end_time - begin_time) << endl;

我认为它将打印我的算法占用的挂钟时间。但是令人惊讶的是,此代码打印的时间比以前的代码打印的cpu时间低得多。所以,我很困惑。请提供打印挂钟时间的代码。

2 个答案:

答案 0 :(得分:2)

这些时间可能降低了噪音。为了获得合理的时间度量,请尝试在循环中多次执行算法:

const int loops = 1000000;
double begin_time, end_time;
begin_time = getUnixTime();

for (int i = 0; i < loops; ++i)
    Algorithm();

end_time = getUnixTime();
cout << (double) (end_time - begin_time) / loops << endl;

答案 1 :(得分:0)

在一个单线程程序中,我得到的时间大致相同:

#include <time.h>
#include <stdio.h>
__attribute((noinline)) void nop(void){}
void loop(unsigned long Cnt) { for(unsigned long i=0; i<Cnt;i++) nop(); }
int main()
{
    clock_t t0,t1;
    struct timespec ts0,ts1;
    t0=clock();
    clock_gettime(CLOCK_REALTIME,&ts0);
    loop(1000000000);
    t1=clock();
    clock_gettime(CLOCK_REALTIME,&ts1);
    printf("clock-diff: %lu\n", (unsigned long)((t1 - t0)/CLOCKS_PER_SEC));
    printf("clock_gettime-diff: %lu\n", (unsigned long)((ts1.tv_sec - ts0.tv_sec)));
}
//prints 2 and 3 or 2 and 2 on my system

但是clock的联机帮助页仅将其描述为返回逼近。没有迹象表明近似值可与clock_gettime返回的结果相媲美。

我得到多个结果的地方是我抛出了多个线程:

#include <time.h>
#include <stdio.h>
#include <pthread.h>
__attribute((noinline)) void nop(void){}
void loop(unsigned long Cnt) {
    for(unsigned long i=0; i<Cnt;i++) nop();
}
void *busy(void *A){ (void)A; for(;;) nop(); }
int main()
{
    pthread_t ptids[4]; 
    for(size_t i=0; i<sizeof(ptids)/sizeof(ptids[0]); i++)
        pthread_create(&ptids[i], 0, busy, 0);
    clock_t t0,t1;
    struct timespec ts0,ts1;
    t0=clock();
    clock_gettime(CLOCK_REALTIME,&ts0);
    loop(1000000000);
    t1=clock();
    clock_gettime(CLOCK_REALTIME,&ts1);
    printf("clock-diff: %lu\n", (unsigned long)((t1 - t0)/CLOCKS_PER_SEC));
    printf("clock_gettime-diff: %lu\n", (unsigned long)((ts1.tv_sec - ts0.tv_sec)));

}
//prints 18 and 4 on my 4-core linux system

这是因为Linux上的musl和glibc都使用clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts)来实现clock(),并且CLOCK_PROCESS_CPUTIME_ID手册页中将clock_gettime非标准时钟描述为所有进程线程的返回时间在一起。