开发者

Calculating time of execution with time() function

I was given the following HomeWork assignment,

Write a progr开发者_运维知识库am 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;
}


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


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.


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜