Multi-threaded runtime

I am trying to measure the runtime of a program with multiple threads. I use this piece of code in the main program to calculate the time:

clock_t startTime = clock(); //do stuff clock_t stopTime = clock(); float secsElapsed = (float)(stopTime - startTime)/CLOCKS_PER_SEC; 

Now I have a problem: for example, I run my program with 4 threads (each thread runs on one core), the execution time is 21.39. I check the system monitor at runtime when the runtime is around 5.3.

It seems that the actual runtime is multiplied by the number of THREADS.

What is the problem?

+6
source share
1 answer

This is because you are tracking the processor time , which is the accumulated time spent on the CPU running your code, and not the Wall time , which is the real time elapsed between your startTime and stopTime .

Valid clock_t :

Returns the processor time spent by the program.

If you do the math: 5.3 * 4 = 21.2 , then what you get means that you have a good multi-threaded code with a speed of 4 .

So, to measure wall time, it is better to use std :: chrono :: high_resolution_clock , and you should return 5.3 , you can also use classic gettimeofday() .

If you use OpenMP for multithreading, you also have omp_get_wtime ()

 double startTime = omp_get_wtime(); // do stuff double stopTime = omp_get_wtime(); double secsElapsed = stopTime - startTime; // that all ! 
+8
source

All Articles