C how to measure time?

This is an "algorithm", but when I want to measure the runtime, it gives me zero. Why?

#define ARRAY_SIZE 10000 ... clock_t start, end; start = clock(); for( i = 0; i < ARRAY_SIZE; i++) { non_parallel[i] = vec[i] * vec[i]; } end = clock(); printf( "Number of seconds: %f\n", (end-start)/(double)CLOCKS_PER_SEC ); 

So what should I do to measure time?

+6
source share
2 answers

Two things:

  • 10000 not much on a modern computer. Therefore, this loop will probably work less than a millisecond - less precision clock() . Therefore, it will return zero.

  • If you are not using the non_parallel result, it is possible that the entire loop will be optimized by the compiler.

Most likely, you just need a more expensive cycle. Try increasing ARRAY_SIZE by something more.


Here is a test on my machine with a large array size:

 #define ARRAY_SIZE 100000000 int main(){ clock_t start, end; double *non_parallel = (double*)malloc(ARRAY_SIZE * sizeof(double)); double *vec = (double*)malloc(ARRAY_SIZE * sizeof(double)); start = clock(); for(int i = 0; i < ARRAY_SIZE; i++) { non_parallel[i] = vec[i] * vec[i]; } end = clock(); printf( "Number of seconds: %f\n", (end-start)/(double)CLOCKS_PER_SEC ); free(non_parallel); free(vec); return 0; } 

Conclusion:

 Number of seconds: 0.446000 
+14
source

This is an unreliable way of the actual number of seconds, since the clock() function is pretty low, and your loop doesn't do a lot of work. You can make your cycle more active so that it runs longer or uses a better synchronization method.

Higher accuracy methods apply to the platform. For Windows, see How to use QueryPerformanceCounter? and for Linux see High Resolution Timer with C ++ and Linux?

+5
source

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


All Articles