在MinGW GCC 8.2.0中正确实现了clock_gettime()吗? [英] Is clock_gettime() correctly implemented in MinGW GCC 8.2.0?
问题描述
我偶然发现了Linux系统中clock_gettime()
函数的存在.由于我正在寻找一种衡量函数执行时间的方法,因此我在Windows 10 64位计算机上的MinGW gcc 8.2.0版本中进行了尝试:
By chance, I found out about the existence of the clock_gettime()
function for Linux systems. Since I'm looking for a way to measure execution time of a function, I tried it in the MinGW gcc 8.2.0 version on a Windows 10 64-bit machine:
#include <time.h>
#include <stdio.h>
int main() {
struct timespec tstart, tend;
clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tstart);
for (int i = 0; i < 100000; ++i);
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &tend);
printf("It takes %li nanoseconds for 100,000 empty iterations.\n", tend.tv_nsec - tstart.tv_nsec);
return 0;
}
此代码段编译时没有警告/错误,并且没有运行时失败(至少没有写入stdout).
This code snippet compiles without warnings/errors, and there are no runtime failures (at least not written to stdout).
输出:
It takes 0 nanoseconds for 100,000 empty iterations.
我不相信这是真的.
您能发现缺陷吗?
还有一件事:
根据 N1570委员会草案(ISO/IEC 9899:201x,2011年4月12日),timespec_get()
是否应该代替clock_gettime()
的角色?
According to the N1570 Committee draft (April 12, 2011) of the ISO/IEC 9899:201x, shouldn't timespec_get()
take the role of clock_gettime()
instead?
推荐答案
该循环应完全优化为零,因此使用低分辨率时钟(分辨率不一定是单个纳秒;它可能以更大的单位前进. clock_getres
应该能够告诉您)0是合理的结果.但是您的代码中还有一些其他错误,例如将CLOCK_THREAD_CPUTIME_ID
与CLOCK_PROCESS_CPUTIME_ID
混合在一起并且不检查clock_gettime
的返回值(这可能表明您不支持这些时钟).
That loop should get optimized out to nothing at all, so with a low resolution clock (resolution is not necessarily individual nanoseconds; it may advance in much larger units which clock_getres
should be able to tell you) 0 is a plausible result. But you have a few other bugs in your code like mixing CLOCK_THREAD_CPUTIME_ID
with CLOCK_PROCESS_CPUTIME_ID
and not checking the return value of clock_gettime
(it might be telling you these clocks aren't supported).
这篇关于在MinGW GCC 8.2.0中正确实现了clock_gettime()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!