我想测量一个特定操作要花费多长时间,因此,我编写了以下代码:
for (int counter2 = 0; counter2 <= 10; counter2++) { // I'll do the test 10 times,
// for having reliable results
time_t ltime;
time(<ime); // What's the time at the beginning?
for (counter = 0; counter <= 1000000; counter++) {
Do_Something();
}
time_t ltime2;
time(<ime2); // What's the time after having launched Do_Something()?
printf("Times:First=[%d], Second=[%d]\n", ltime, ltime2);
}
我期望的是类似的东西
Times: First=[1559574983], Second=[1559574985]
Times: First=[1559574990], Second=[1559574999]
相反,我得到了:
Times: First=[1559574983], Second=[0]
Times: First=[1559574990], Second=[0]
我已经调试过了,ltime2
似乎是正确的。我在做什么错了?
答案 0 :(得分:4)
"%d"
格式不是您的正确选择,但是您不必照顾支持time_t
的类型,只需替换
printf("Times:First=[%d], Second=[%d]\n", ltime, ltime2);
作者
std::cout << "Times:First=[" << ltime << "], Second=[" << ltime2 << "]" << std::endl;
如果出于某种未知原因,您真的想使用@ Lightness Races in Orbit 3 建议的C printf ,可以将值转换为其他类型(跳变足够长的时间),并使用与该类型兼容的格式,请参见Format specifier to print time(0) in C
答案 1 :(得分:0)
感谢您的快速答复。
仅作记录,这里是我使用的最终解决方案(结合了mentioned other Stackoverflow post和difftime()
函数):
printf("First=[%ju], Second=[%ju], Difference=[%f]\n", (uintmax_t) ltime,
(uintmax_t) ltime2,
difftime(ltime2, ltime));