不良结果:时间(NULL)和时钟()
#import <stdio.h>
#import <time.h>
int main (void) {
printf("Clock ticks per second: %d\n", CLOCKS_PER_SEC);
double check = clock();
int timex = time(NULL);
for (int x = 0; x <= 500000; x++) {
printf(".");
}
puts("\n");
printf("Total Time by Clock: %7.7f\n", (clock() - check) / CLOCKS_PER_SEC );
printf("Total Time by Time: %d\n", time(NULL) - timex);
getchar();
}
当我执行上面的代码时,我得到的结果如下:
按时钟列出的总时间:0.0108240
按时间列出的总时间:12
我希望 Clock() 表示尽可能接近时间的数字。
上面给出的总时间是在 MacBook 上完成的,但是,代码在我的笔记本电脑(Windows)上运行得很好。
CLOCKS_PER_SECOND 宏在 PC 上返回 1000,在 MAC 上返回 1,000,000。
#import <stdio.h>
#import <time.h>
int main (void) {
printf("Clock ticks per second: %d\n", CLOCKS_PER_SEC);
double check = clock();
int timex = time(NULL);
for (int x = 0; x <= 500000; x++) {
printf(".");
}
puts("\n");
printf("Total Time by Clock: %7.7f\n", (clock() - check) / CLOCKS_PER_SEC );
printf("Total Time by Time: %d\n", time(NULL) - timex);
getchar();
}
When I execute the above code I get results like:
Total Time by Clock: 0.0108240
Total Time by Time: 12
I would like to have clock() represent a number as close to as possible as time.
The total time presented above was done on a macbook, however, the code works excellent on my laptop (windows).
The CLOCKS_PER_SECOND macro returns 1000 on the PC, 1,000,000 on the MAC.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Windows 上的 Clock() 返回挂钟时间。 *nixes 上的 Clock() 返回程序所花费的 CPU 时间,这不会很多,在这里执行 I/O 时可能会被阻塞。
clock() on windows returns the wall clock time. clock() on *nixes return the CPU time your program has spent, which is not going to be a lot, you're likely blocked when doing I/O here.
控制台的 printf() 为每个函数调用进行系统调用,并且在控制台重绘等中阻塞的时间不计入处理时间。
在那里进行一些繁重的计算。
printf() to console makes system call for each functon call, and time spent blocked in console redrawing, etc. do not count for process time.
Make some heavy calculations there.
time()
返回一个time_t
。当您将其分配给int
时,您可能会丢失信息。如果您始终使用time_t
会发生什么?time()
returns atime_t
. When you assign that to anint
it is possible that you lose information. What happens if you usetime_t
throughout?