在 C 中测量时间 [英] Measuring time in C

查看:25
本文介绍了在 C 中测量时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试测量 C(矩阵乘法)中的一些活动,并注意到我应该做这样的事情:

I'm trying to measure some activity in C (Matrix multiplying) and noticed that I should do something like this:

clock_t start = clock();
sleep(3);
clock_t end = clock();
double elapsed_time = (end - start)/(double)CLOCKS_PER_SEC;
printf("Elapsed time: %.2f.
", elapsed_time);

输出为:

Elapsed time: 0.00.

为什么会这样?

推荐答案

clock 估计你的程序使用的 CPU 时间;这就是 CPU 忙于执行属于您的程序的指令的时间.sleep 不执行任何工作,因此不会占用明显的 CPU 时间(即使需要挂钟时间).

clock estimates the CPU time used by your program; that's the time the CPU has been busy executing instructions belonging to your program. sleep doesn't perform any work, so it takes no noticeable CPU time (even if it takes wallclock time).

如果你想测量挂钟时间,使用time:

If you want to measure wallclock time, use time:

time_t start = time(NULL);
sleep(3);
printf("%.2f
", (double)(time(NULL) - start));

将打印一个接近三的数字.

will print a number close to three.

这篇关于在 C 中测量时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆