calculating time elapsed in C++
Using <chrono>
, the code you need could look like this:
using clock = std::chrono::system_clock;
using sec = std::chrono::duration<double>;
// for milliseconds, use using ms = std::chrono::duration<double, std::milli>;
const auto before = clock::now();
someFunctionToMeasure();
const sec duration = clock::now() - before;
std::cout << "It took " << duration.count() << "s" << std::endl;
NB: Thanks to Howard for his helpful comments for the above.
If you need this snippet multiple times and start/end are approximately entry and exit points of the scope in which you invoke someFunctionToMeasure()
, it might make sense to wrap it into a utility class that makes the two calls to now()
in constructor and destructor.
How to measure elapsed time without being affected by changes in system time
You can file a bug with your vendor.
From the standard:
Objects of class
steady_clock
represent clocks for which values oftime_point
never decrease as physical time advances and for which
values oftime_point
advance at a steady rate relative to real
time. That is, the clock may not be adjusted.
If you can find a reliable source of monotonic time on your system, you can easily wrap that source in a custom chrono::clock
and subsequently still make use of the type-safe chrono system. For example:
#include <chrono>
struct MyClock
{
using duration = std::chrono::nanoseconds;
using rep = duration::rep;
using period = duration::period;
using time_point = std::chrono::time_point<MyClock>;
static constexpr bool is_steady = true;
static time_point now() noexcept
{
using namespace std::chrono;
timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return time_point{seconds{ts.tv_sec} + nanoseconds{ts.tv_nsec}};
}
};
Now you can say things like:
MyClock::time_point t = MyClock::now();
// ...
MyClock::time_point t2 = MyClock::now();
std::cout << "ELAPSED: " << std::chrono::duration_cast<std::chrono::seconds>(t2-t).count() << std::endl;
Measure elapsed time in C?
The C Standard does not define a portable way to do this. The time()
library function has a definition of 1 second, which is inappropriate for your purpose. As mentioned by @Puck, C11 did introduce timespec_get()
to retrieve a more precise time value, but this function is not widely supported and may not provide the expected accuracy.
Other functions are available on selected systems:
The POSIX standard defines
gettimeofday()
andclock_gettime()
which can return precise real time with the argumentCLOCK_REALTIME
.OS/X has a more precise alternative:
clock_gettime_nsec_np
which returns a 64-bit value in nanosecond increments.Microsoft documents this for Windows.
Note however that performing precise and reliable sub-microsecond benchmarks is a difficult game to say the least.
Why are there a big difference when measuring elapsed time according to where to measure?
Taking a snapshot of the time before std::cin >> a >> b;
leads to an inaccurate measurement as you're likely starting the clock before you type in the values for a
and b
. Generally you want to put your timing as close as possible to the thing you're actually measuring.
Measure time elapsed in C++ [duplicate]
#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;
}
Cleanest and simplest way to get elapsed time since execution in C++
The new <chrono>
functions take a little getting used to but they make things fairly easy when you get to know how they work.
Your problem could be solved like this for example:
#include <chrono>
#include <thread>
#include <iostream>
// for readability
using hr_clock = std::chrono::high_resolution_clock;
using hr_time_point = hr_clock::time_point;
using hr_duration = hr_clock::duration;
using milliseconds = std::chrono::milliseconds;
int main()
{
// note the program start time
hr_time_point prog_start = hr_clock::now();
// do stuff
std::this_thread::sleep_for(milliseconds(1000));
// find the duration
hr_duration d = hr_clock::now() - prog_start;
// cast the duration to milliseconds
milliseconds ms = std::chrono::duration_cast<milliseconds>(d);
// print out the number of milliseconds
std::cout << "time passed: " << ms.count() << " milliseconds.\n";
}
For convenience you could create a function to return the time since that function was last called:
milliseconds since_last_call()
{
// retain time between calls (static)
static hr_time_point previous = hr_clock::now();
// get current time
hr_time_point current = hr_clock::now();
// get the time difference between now and previous call to the function
milliseconds ms = std::chrono::duration_cast<milliseconds>(current - previous);
// store current time for next call
previous = current;
// return elapsed time in milliseconds
return ms;
}
int main()
{
since_last_call(); // initialize functions internal static time_point
// do stuff
std::this_thread::sleep_for(milliseconds(1000));
milliseconds ms = since_last_call();
// print out the number of milliseconds
std::cout << "time passed: " << ms.count() << " milliseconds.\n";
}
Related Topics
Start Thread With Member Function
Is Gcc 4.8 or Earlier Buggy About Regular Expressions
How to Detect Unsigned Integer Overflow
What Are All the Common Undefined Behaviours That a C++ Programmer Should Know About
Array Index Out of Bound Behavior
How to Test Whether Stringstream Operator≫≫ Has Parsed a Bad Type and Skip It
Why Do People Say There Is Modulo Bias When Using a Random Number Generator
Why Have Header Files and .Cpp Files
When a Function Has a Specific-Size Array Parameter, Why Is It Replaced With a Pointer
Output Unicode Strings in Windows Console App
Does a Const Reference Class Member Prolong the Life of a Temporary
What Are the Rules For Calling the Base Class Constructor
How to Print Current Time (With Milliseconds) Using C++/C++11