使用 time() 函数计算执行时间
我被分配了以下家庭作业,
编写一个程序在你的计算机上测试需要多长时间才能完成 nlogn、n2、n5、2n 和 n! n=5、10、15、20 的添加。
我写了一段代码,但执行时间始终为 0。任何人都可以帮我解决这个问题吗?谢谢
#include <iostream>
#include <cmath>
#include <ctime>
using namespace std;
int main()
{
float n=20;
time_t start, end, diff;
start = time (NULL);
cout<<(n*log(n))*(n*n)*(pow(n,5))*(pow(2,n))<<endl;
end= time(NULL);
diff = difftime (end,start);
cout <<diff<<endl;
return 0;
}
I was given the following HomeWork assignment,
Write a program to test on your computer how long it takes to do
nlogn, n2, n5, 2n, and n! additions for n=5, 10, 15, 20.
I have written a piece of code but all the time I am getting the time of execution 0. Can anyone help me out with it? Thanks
#include <iostream>
#include <cmath>
#include <ctime>
using namespace std;
int main()
{
float n=20;
time_t start, end, diff;
start = time (NULL);
cout<<(n*log(n))*(n*n)*(pow(n,5))*(pow(2,n))<<endl;
end= time(NULL);
diff = difftime (end,start);
cout <<diff<<endl;
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
比秒精度的 time() 更好的是使用毫秒精度。
一种便携式方式是例如
better than time() with second-precision is to use a milliseconds precision.
a portable way is e.g.
循环执行每个计算数千次,这样您就可以克服
时间
的低分辨率并获得有意义的结果。请记住在报告结果时除以迭代次数。这不是特别准确,但这对于本次作业可能并不重要。
Execute each calculation thousands of times, in a loop, so that you can overcome the low resolution of
time
and obtain meaningful results. Remember to divide by the number of iterations when reporting results.This is not particularly accurate but that probably does not matter for this assignment.
至少在类 Unix 系统上,
time()
只给你 1 秒的粒度,所以它对于计时那些需要很短时间的事情没有用(除非你在一个时间段中多次执行它们)环形)。看一下gettimeofday()
函数,它为您提供微秒分辨率的当前时间。或者考虑使用clock()
,它测量CPU时间而不是挂钟时间。At least on Unix-like systems,
time()
only gives you 1-second granularity, so it's not useful for timing things that take a very short amount of time (unless you execute them many times in a loop). Take a look at thegettimeofday()
function, which gives you the current time with microsecond resolution. Or consider usingclock()
, which measure CPU time rather than wall-clock time.您的代码执行速度太快,无法被返回经过秒数的 time 函数检测到自 UTC 时间 1970 年 1 月 1 日 00:00 开始。
尝试使用这段代码:
要使用它,您必须包含 sys/timeb.h。
实际上,更好的做法是在循环中重复计算以获得更精确的结果。
Your code is executed too fast to be detected by time function returning the number of seconds elapsed since 00:00 hours, Jan 1, 1970 UTC.
Try to use this piece of code:
To use it you have to include sys/timeb.h.
Actually the better practice is to repeat your calculations in the loop to get more precise results.
您可能需要找到更精确的特定于平台的计时器,例如 Windows 高性能计时器。您还可能(很可能)发现您的编译器优化或删除了几乎所有代码。
You will probably have to find a more precise platform-specific timer such as the Windows High Performance Timer. You may also (very likely) find that your compiler optimizes or removes almost all of your code.