I want to measure the runtime of my C++ code. Executing my code takes about 12 hours and I want to write this time at the end of execution of my code. How can I do it in my code?
Operating system: Linux
If you are using C++11 you can use system_clock::now():
auto start = std::chrono::system_clock::now(); /* do some work */ auto end = std::chrono::system_clock::now(); auto elapsed = end - start; std::cout << elapsed.count() << '\n'; You can also specify the granularity to use for representing a duration:
// this constructs a duration object using milliseconds auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start); // this constructs a duration object using seconds auto elapsed = std::chrono::duration_cast<std::chrono::seconds>(end - start); If you cannot use C++11, then have a look at chrono from Boost.
The best thing about using such a standard libraries is that their portability is really high (e.g., they both work in Linux and Windows). So you do not need to worry too much if you decide to port your application afterwards.
These libraries follow a modern C++ design too, as opposed to C-like approaches.
EDIT: The example above can be used to measure wall-clock time. That is not, however, the only way to measure the execution time of a program. First, we can distinct between user and system time:
Depending on the objectives it may be necessary or not to consider system time as part of the execution time of a program. For instance, if the aim is to just measure a compiler optimization on the user code then it is probably better to leave out system time. On the other hand, if the user wants to determine whether system calls are a significant overhead, then it is necessary to measure system time as well.
Moreover, since most modern systems are time-shared, different programs may compete for several computing resources (e.g., CPU). In such a case, another distinction can be made:
For measuring CPU time, Boost includes a set of extra clocks:
process_real_cpu_clock, captures wall clock CPU time spent by the current process.process_user_cpu_clock, captures user-CPU time spent by the current process.process_system_cpu_clock, captures system-CPU time spent by the current process. A tuple-like class process_cpu_clock, that captures real, user-CPU, and system-CPU process times together.thread_clock thread steady clock giving the time spent by the current thread (when supported by a platform).Unfortunately, C++11 does not have such clocks. But Boost is a wide-used library and, probably, these extra clocks will be incorporated into C++1x at some point. So, if you use Boost you will be ready when the new C++ standard adds them.
Finally, if you want to measure the time a program takes to execute from the command line (as opposed to adding some code into your program), you may have a look at the time command, just as @BЈовић suggests. This approach, however, would not let you measure individual parts of your program (e.g., the time it takes to execute a function).
system_clock can jump (due to user changing system time, NTP adjusting clock, leap seconds being inserted). It's useless for measurement of time intervals.std::chrono::steady_clock, or clock_gettime() if you can't use C++11. Never ever the system clock. It's designed for an entirely different purpose and does not aim to be steady or monotonically increasing, and is therefore not fit for this purpose. Ever. The other answer is better.cout this? std::chrono::duration_cast<std::chrono::seconds>(end - start);Use std::chrono::steady_clock and not std::chrono::system_clock for measuring run time in C++11. The reason is (quoting system_clock's documentation):
on most systems, the system time can be adjusted at any moment
while steady_clock is monotonic and is better suited for measuring intervals:
Class std::chrono::steady_clock represents a monotonic clock. The time points of this clock cannot decrease as physical time moves forward. This clock is not related to wall clock time, and is best suitable for measuring intervals.
Here's an example:
auto start = std::chrono::steady_clock::now(); // do something auto finish = std::chrono::steady_clock::now(); double elapsed_seconds = std::chrono::duration_cast< std::chrono::duration<double>>(finish - start).count(); A small practical tip: if you are measuring run time and want to report seconds std::chrono::duration_cast<std::chrono::seconds> is rarely what you need because it gives you whole number of seconds. To get the time in seconds as a double use the example above.
std::chrono::duration_cast<std::chrono::seconds> the way to get the difference between two time points as total seconds?std::chrono::duration_cast<std::chrono::seconds> will return 0 if the difference is less than a second. If you want duration as a floating-point number then use double instead of seconds.You can use time to start your program. When it ends, it print nice time statistics about program run. It is easy to configure what to print. By default, it print user and CPU times it took to execute the program.
EDIT : Take a note that every measure from the code is not correct, because your application will get blocked by other programs, hence giving you wrong values*.
* By wrong values, I meant it is easy to get the time it took to execute the program, but that time varies depending on the CPUs load during the program execution. To get relatively stable time measurement, that doesn't depend on the CPU load, one can execute the application using time and use the CPU as the measurement result.
time as suggested, you don't have to decide. It reports both elapsed time and CPU time.time it is not a bad solution if you want to measure the execution time from the command line. I was just against the idea that measuring CPU time is the only valuable measurement of the time it takes for a program to run (as the reply to EitanT was suggesting).I used something like this in one of my projects:
#include <sys/time.h> struct timeval start, end; gettimeofday(&start, NULL); //Compute gettimeofday(&end, NULL); double elapsed = ((end.tv_sec - start.tv_sec) * 1000) + (end.tv_usec / 1000 - start.tv_usec / 1000); This is for milliseconds and it works both for C and C++.
start and end gives the number of seconds and microseconds since start of epoch: man7.org/linux/man-pages/man2/gettimeofday.2.htmlgettimeofday() to measure time. So many bugs all over due to this. If you must use pre-C++11, then use clock_gettime() with a monotonic clock.This is the code I use:
const auto start = std::chrono::steady_clock::now(); // Your code here. const auto end = std::chrono::steady_clock::now(); std::chrono::duration<double> elapsed = end - start; std::cout << "Time in seconds: " << elapsed.count() << '\n'; You don't want to use std::chrono::system_clock because it is not monotonic! If the user changes the time in the middle of your code your result will be wrong - it might even be negative. std::chrono::high_resolution_clock might be implemented using std::chrono::system_clock so I wouldn't recommend that either.
This code also avoids ugly casts.
If you wish to print the measured time with printf(), you can use this:
auto start = std::chrono::system_clock::now(); /* measured work */ auto end = std::chrono::system_clock::now(); auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start); printf("Time = %lld ms\n", static_cast<long long int>(elapsed.count())); system_clock, time(), or gettimeofday() to measure durations. It's a time bomb (no pun intended) waiting to explode. Use steady_clock or clock_gettime().You could also try some timer classes that start and stop automatically, and gather statistics on the average, maximum and minimum time spent in any block of code, as well as the number of calls. These cxx-rtimer classes are available on GitHub, and offer support for using std::chrono, clock_gettime(), or boost::posix_time as a back-end clock source.
With these timers, you can do something like:
void timeCriticalFunction() { static rtimers::cxx11::DefaultTimer timer("expensive"); auto scopedStartStop = timer.scopedStart(); // Do something costly... } with timing stats written to std::cerr on program completion.
timecommand when you start whatever program.