程序计时的小技巧:clock()和wtime()

xiaoxiao2021-02-28  97

clock()

clock()是在time.h里面的程序,通过前后两次相减得到ticktok的次数,除以CLOCKS_PER_SEC,就得到了秒数。

在计算一个程序的运行时间的时候,如果只是简单的线性执行的程序,那么使用clock() 就可以计算出程序的执行时间,但是其实这个时间是CPU的时间。如果你用clock()计算并行程序执行时间,发现它会把所有CPU的执行都叠加起来【1】。

clock_t end_test = clock(); printf("Traing CPU time:%u\n", (unsigned)(end_train - start)); printf("Traing CPU time with second:%fs\n", (float)(end_train - start)*1.0/(CLOCKS_PER_SEC*1.0));

wtime()

在并行程序中比如OpenMP、CUDA中怎么获取时间呢,我们得到的是绝对世界时间,那么就可以比较容易获得程序执行时间【2】。

一般写法如下:

double wtime(void) { double now_time; struct timeval etstart; if (gettimeofday(&etstart, NULL) == -1) perror("Error: calling gettimeofday() not successful.\n"); now_time = ((etstart.tv_sec) * 1000 + etstart.tv_usec / 1000.0); return now_time; }

参考链接: 【1】clock(): http://blog.csdn.net/sinat_15799399/article/details/45697589 【2】wtime(): http://blog.csdn.net/lavorange/article/details/41942323

转载请注明原文地址: https://www.6miu.com/read-55857.html

最新回复(0)