Calculating time of execution with time() function

元气小坏坏 提交于 2019-11-27 04:54:37

问题


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;
}

回答1:


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.




回答2:


better than time() with second-precision is to use a milliseconds precision. a portable way is e.g.

int main(){
clock_t start, end;
double msecs;

start = clock();
/* any stuff here ... */
end = clock();
msecs = ((double) (end - start)) * 1000 / CLOCKS_PER_SEC;
return 0;
}



回答3:


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 the gettimeofday() function, which gives you the current time with microsecond resolution. Or consider using clock(), which measure CPU time rather than wall-clock time.




回答4:


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:

inline long getCurrentTime() {
    timeb timebstr;
    ftime( &timebstr );
    return (long)(timebstr.time)*1000 + timebstr.millitm;
}

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.




回答5:


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.



来源:https://stackoverflow.com/questions/6974893/calculating-time-of-execution-with-time-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!