Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

execution time in multithreading environment

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??

like image 271
stella Avatar asked Jul 09 '15 08:07

stella


People also ask

How is thread execution time calculated?

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.

What is multithreaded execution?

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.

Do threads execute at the same time?

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.

Does multithreading save time?

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.


1 Answers

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 !
like image 141
coincoin Avatar answered Sep 29 '22 01:09

coincoin