我需要在程序本身内部对我的 C 程序进行计时(因为我对代码的多个小节进行计时并输出它们的时间)。它必须以(至少)毫秒的精度完成。我的理解是“time.h”函数仅适用于秒。还有其他方法可以做到这一点吗?
最佳答案
您可以使用函数clock()
来自<time.h>
:
The clock() function returns an approximation of processor time used by the program.
将返回值除以宏 CLOCKS_PER_SEC
获取以秒为单位的时间量,如果您想要以毫秒为单位的时间,可以将该值乘以 1000,即:
double get_time_as_ms(void) {
return ((double)(clock() * 1000) / CLOCKS_PER_SEC);
}
或者更准确地说,有一个开始和结束clock_t
然后计算差异:
double duration_as_ms(clock_t start, clock_t end) {
return ((double)(end - start) * 1000) / CLOCKS_PER_SEC;
}
clock_t start = clock(); /* start of program */
/* ... */
clock_t end = clock(); /* end of program */
/* ... */
printf("Duration: %fms\m", duration_as_ms(start, end));
编辑:只是想添加 CLOCKS_PER_SEC
的通用值是 1000000
,表示 clock()
返回的值将是十万分之一秒。因此它精确到千分之一毫秒(一微秒)。
关于c - C 语言定时程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8408946/