0

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.

2
  • 1
    Why don't you want to use time.h? Commented Jul 1, 2010 at 16:58
  • I am not opposed to it but I generally don't like to mix and match c and c++ code. Commented Jul 1, 2010 at 17:00

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1. Remember that if you use the C++ headers the symbols will be defined inside the std namespace, so it will be std::clock
3

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.

5 Comments

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.
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- 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).
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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.