Calculating runtime using the time function ()

I was assigned the following HomeWork assignment,

Write a program to test on your computer how long it will take to run nlogn, n2, n5, 2n and n! additives for n = 5, 10, 15, 20.

I wrote a piece of code, but all the time I get runtime 0. Can someone help me 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; } 
0
source share
5 answers

Perform each calculation thousands of times in a cycle so that you can overcome the low resolution time and get meaningful results. Remember to divide by the number of iterations when presenting the results.

This is not particularly accurate, but it probably does not matter for this purpose.

+3
source

better than time () with second precision - use millisecond precision. for example, a portable method.

 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; } 
+4
source

At least on Unix-like systems, time() gives you only 1 second granularity, so this is not useful for picking a time that takes a very short time (unless you execute them many times in a loop). Take a look at the gettimeofday() function, which gives you the current time in microsecond resolution. Or use clock() , which measures the processor time, not the wall clock time.

+2
source

Your code is running too fast to be detected by the time function, which returns the number of seconds elapsed from 00:00 hours, January 1, 1970 UTC.

Try using this piece of code:

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

To use it, you must enable sys / timeb.h.

Actually, the best practice is to repeat your calculations in a loop to get more accurate results.

+1
source

You may have to find a more accurate timer for a specific platform, such as a high-performance Windows timer. You may also (very likely) find that your compiler optimizes or removes almost all of your code.

+1
source

Source: https://habr.com/ru/post/1440211/


All Articles