I
I
Igor Petrov2012-03-22 22:52:05
C++ / C#
Igor Petrov, 2012-03-22 22:52:05

Measure the execution time of an algorithm?

Hello!
Tell me, pliz, how to measure the execution time of an algorithm in C under Linux?
At the moment, I use the time.h library

clock_t startClock, endClock;<br/>
startClock = clock();<br/>
//Код<br/>
endClock = clock();<br/>
diff = difftime(endClock, startClock);<br/>

But if there are too few operations, I always get 0 at the output.
I would like something more precise, as, for example, in Java System.nanoTime().

Answer the question

In order to leave comments, you need to log in

3 answer(s)
L
leventov, 2012-03-22
@leventov

Just to be more specific -

typedef unsigned long long ull;

inline ull rdtsc() {
  unsigned int lo, hi;
  asm volatile ( "rdtsc\n" : "=a" (lo), "=d" (hi) );
  return ((ull)hi << 32) | lo;
}
instead of clock.
I can write an article on how to measure small pieces of C-code without any error.

B
BrainHacker, 2012-03-22
@BrainHacker

If you just want to know how long the algorithm takes, then there is a standard scheme:
1. Start a timer.
2. Run the algorithm N times.
3. Stop the timer and measure the time.
Then the execution time of the algorithm once will be equal to <measured_time> / N. The larger N, the more accurate the value.

H
huankun, 2012-03-23
@huankun

man gettimeofday
measuring time with microsecond precision (under Linux)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question