What's the best way to calculate a time difference in C++? I'm timing the execution speed of a program, so I'm interested in milliseconds. Better yet, seconds.milliseconds..
The accepted answer works, but needs to include ctime or time.h as noted in the comments.
To calculate the time difference in minutes, you need to multiply the resulting value by the total number of minutes in a day (which is 1440 or 24*60). Suppose you have a data set as shown below and you want to calculate the total number of minutes elapsed between the start and the end date.
We can use the clock() function provided by the <time. h> header file to calculate the CPU time consumed by a task within a C application. It returns the clock_t type, which stores the total number of clock ticks.
See std::clock()
function.
const clock_t begin_time = clock(); // do something std::cout << float( clock () - begin_time ) / CLOCKS_PER_SEC;
If you want calculate execution time for self ( not for user ), it is better to do this in clock ticks ( not seconds ).
EDIT:
responsible header files - <ctime>
or <time.h>
I added this answer to clarify that the accepted answer shows CPU time which may not be the time you want. Because according to the reference, there are CPU time and wall clock time. Wall clock time is the time which shows the actual elapsed time regardless of any other conditions like CPU shared by other processes. For example, I used multiple processors to do a certain task and the CPU time was high 18s where it actually took 2s in actual wall clock time.
To get the actual time you do,
#include <chrono> auto t_start = std::chrono::high_resolution_clock::now(); // the work... auto t_end = std::chrono::high_resolution_clock::now(); double elapsed_time_ms = std::chrono::duration<double, std::milli>(t_end-t_start).count();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With