views:

132

answers:

2

I need to calculate the execution time of a C++ program. I am currently using the c-style head, <time.h> with the following code:

clock_t tStart = clock();
...
printf("Execution Time: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);

Is there a c++ header I can use to calculate execution time? Please note this needs to be cross-platform compatible.

+4  A: 

The time and clock functions are one of those things that vary from platform to platform.

I like to use Boost's timer library for what you are trying to do: http://www.boost.org/doc/libs/1_43_0/libs/timer/timer.htm as it works well cross platform, and is quite straightforward to use.

MarkD
Depends if you want Wall or CPU Time. e.g. On OpenVMS it gives CPU Time, but on most flavours of Linux it provides Wall Time.
Salgar
`clock()` and `time()` shouldn't vary from platform to platform (apart from the value of `CLOCKS_PER_SEC`, and whether they work at all), since they're part of the C standard.
Mike Seymour
@Mike- I was under the impression that, as Salgar pointed out, clock and time can differ in terms of providing CPU time or wall time depending on the implementation. Or at least at some point, I believe this was the case (I've been using boost::timer for quite a long time because of some issues that I can't recall the details on, long long ago).
MarkD
@MarkD: If the implementation follows the standard, then `clock()` will give process time, and `time()` will give wall time. Otherwise, `boost::timer` will work if Boost knows about that particular implementation, and can detect it and fix its quirks. If you've got a seriously wonky implementation, then you're on your own.
Mike Seymour
Thank you for the clarification Mike. Perhaps I am remembering a standards issue from long ago, or perhaps long ago I had a seriously wonky implementation.
MarkD
+2  A: 

You can use the C++ versions of C headers. Add 'c' at the beginning, and remove '.h'

So you need

#include <ctime>

The rest stays the same, as you can just use the C approach.

Michał Trybus
+1. Remember that if you use the C++ headers the symbols will be defined inside the `std` namespace, so it will be `std::clock`
David Rodríguez - dribeas
That's right, I forgot about it.
Michał Trybus