I am trying to measure a multi-thread program's execution time. I've use this piece of code in main program for calculating time:
clock_t startTime = clock();
//do stuff
clock_t stopTime = clock();
float secsElapsed = (float)(stopTime - startTime)/CLOCKS_PER_SEC;
Now the problem i have is: for example I run my program with 4 thread(each thread running on one core), the execution time is 21.39 . I check my system monitor in run time, where the execution time is about 5.3.
It seems that the actual execution time is multiplied by the number of THREADS.
What is the problem??
How do you calculate: Log time intervals when the thread starts and at swap-in and swap-out. Aggregate all of them and you'll have the execution time of your thread.
Multithreading is a model of program execution that allows for multiple threads to be created within a process, executing independently but concurrently sharing process resources. Depending on the hardware, threads can run fully parallel if they are distributed to their own CPU core.
In the same multithreaded process in a shared-memory multiprocessor environment, each thread in the process can run concurrently on a separate processor, resulting in parallel execution, which is true simultaneous execution.
Few more advantages of Multithreading are:Multithreading saves time as you can perform multiple operations together. The threads are independent, so it does not block the user to perform multiple operations at the same time and also, if an exception occurs in a single thread, it does not affect other threads.
It is because you are monitoring the CPU time which is the accumulated time spent by CPU executing your code and not the Wall time which is the real-world time elapsed between your startTime
and stopTime
.
Indeed clock_t :
Returns the processor time consumed by the program.
If you do the maths : 5.3 * 4 = 21.2
which is what you obtain meaning that you have good multithreaded code with a speedup of 4
.
So to measure the wall time, you should rather use std::chrono::high_resolution_clock for instance and you should get back 5.3
. You can also use the 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's all !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With