为什么我的第二个 time_t 变量没有正确显示
Why is my second time_t variable not shown correctly
我想测量一个特定操作需要多长时间,因此我编写了以下代码:
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
似乎是正确的。我做错了什么?
格式 "%d"
不适合您的情况,但您不必处理支持 time_t
的类型,只需替换
printf("Times:First=[%d], Second=[%d]\n", ltime, ltime2);
来自
std::cout << "Times:First=[" << ltime << "], Second=[" << ltime2 << "]" << std::endl;
如果出于某种不明原因你真的想使用@Lightness Races 在中提出的 C printf评论中的 Orbit 3 您可以将该值转换为其他类型(跳跃足够长)并使用与该类型兼容的格式,请参阅 Format specifier to print time(0) in C
感谢您的快速回复。
仅作记录,在此我使用的最终解决方案(结合 mentioned other Whosebug post 和 difftime()
函数):
printf("First=[%ju], Second=[%ju], Difference=[%f]\n", (uintmax_t) ltime,
(uintmax_t) ltime2,
difftime(ltime2, ltime));
我想测量一个特定操作需要多长时间,因此我编写了以下代码:
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
似乎是正确的。我做错了什么?
格式 "%d"
不适合您的情况,但您不必处理支持 time_t
的类型,只需替换
printf("Times:First=[%d], Second=[%d]\n", ltime, ltime2);
来自
std::cout << "Times:First=[" << ltime << "], Second=[" << ltime2 << "]" << std::endl;
如果出于某种不明原因你真的想使用@Lightness Races 在中提出的 C printf评论中的 Orbit 3 您可以将该值转换为其他类型(跳跃足够长)并使用与该类型兼容的格式,请参阅 Format specifier to print time(0) in C
感谢您的快速回复。
仅作记录,在此我使用的最终解决方案(结合 mentioned other Whosebug post 和 difftime()
函数):
printf("First=[%ju], Second=[%ju], Difference=[%f]\n", (uintmax_t) ltime,
(uintmax_t) ltime2,
difftime(ltime2, ltime));