1

Possible Duplicate:
fast elapsed time on linux

How can I measure how long a function takes to execute in C++? It would be best if I could get the time to a fraction of a millisecond, but if not accuracy to one millisecond should be good enough. I'm running Ubuntu 11.04 if that means anything.

Community
  • 1
  • 1
John Stimac
  • 5,335
  • 8
  • 40
  • 60

2 Answers2

5

The best clock for performance measurement is system-wide real-time clock. In Linux, you can use clock_gettime function with CLOCK_MONOTONIC or CLOCK_MONOTONIC_RAW. Those will give you nanosecond precision.

-2
#include <ctime>
int main(){
    clock_t start = clock();
    // your program goes here
    clock_t ends = clock();
    cout << "Time elapsed: " << (double) (ends - start) / CLOCKS_PER_SEC << endl;
    return 0;
}
ʇolɐǝz ǝɥʇ qoq
  • 717
  • 1
  • 15
  • 30
Benny Tjia
  • 4,853
  • 10
  • 39
  • 48
  • 2
    This is very low precision approximation rather than elapsed time. Division by CLOCKS_PER_SEC also looks odd as this is a hard-coded macro that doesn't really represent a number of clocks per second. Plus, it is not a wall clock. So if you real-time process was swapped out, it will give you some totally weird results... :-] –  Jun 24 '11 at 20:39
  • 1
    How accurate is that going to be? – John Stimac Jun 24 '11 at 20:41
  • 1
    @Vlad: clock_gettime is an adequate alternative i guess.. – Benny Tjia Jun 24 '11 at 20:44
  • This works for me pretty accurately, but it's definitely not the best way to do this. – ʇolɐǝz ǝɥʇ qoq Jun 27 '14 at 05:33