Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to measure the time that a piece of code takes to execute?

Suppose I want to measure the time that a certain piece of code takes. For that I would normally do something like this

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

What if the program is multithreaded and context switches occur within the part which I want to measure? How would I measure the time that my code takes to execute excluding time spent on other threads? Even if there are tools that do it, I would very much like to know how they're doing it.

like image 728
Armen Tsirunyan Avatar asked Sep 21 '11 09:09

Armen Tsirunyan


People also ask

How is code execution time calculated?

The Start() method starts measuring time for executing the code until we call the Stop() method. The ElapsedMilliseconds property gets the total time measured by the current instance in milliseconds. Here, it will return the time taken in executing the for loop.

Which module can say how long your code took to run?

This module provides a simple way to time small bits of Python code. It has both a Command-Line Interface as well as a callable one. It avoids a number of common traps for measuring execution times.

How do you calculate runtime in C++?

Measure execution time of a function in C++ We can find out the time taken by different parts of a program by using the std::chrono library introduced in C++ 11.


Video Answer


1 Answers

There are different ways to measure how long code takes to execute.

If you are interested in the relative performance of certain functions, a profiler is the only way to go. Note that this will de-emphasise the impact of blocking I/O due to the computation overheads it induces.

If you want the clock-based time of certain functions, there are loads of options.

Personally I would say gettimeofday is sufficient.

If you want to get precise, use RDTSC

If you want to get really precise, you'll want something like this

t1 = rdtsc();
t2 = rdtsc();
my_code();
t3 = rdtsc();
my_code_time = (t3-t2) - (t2-t1)

You will need to repeat this block to account for thread scheduling discrepencies, and also pay attention to cacheing effects.

like image 184
spraff Avatar answered Oct 03 '22 20:10

spraff