I'm looking for a C++11 version of the <ctime>
library. Were any like this included with C++11?
EDIT: Anything with more functionality would be perfect!
EDIT 2: I'm looking to use this with a game I'm making so that I can keep track of total time played. Anything that would help me with that is what I'm looking for.
C++11 includes the <chrono>
header, which provides different types of clocks (I'll use the high resolution one), that have a now
function. You can subtract two of these times received from now()
to get the total number of <unit>
s (I'll use seconds) between them:
using clock = std::chrono::high_resolution_clock;
using unit = std::chrono::seconds;
std::chrono::time_point<clock> startTime = clock::now(); //get starting time
... //do whatever stuff you have to do
std::chrono::time_point<clock> thisTime = clock::now();
long long secondsElapsed = std::chrono::duration_cast<unit>(thisTime - startTime).count();
//now use secondsElapsed however you wish
//you can also use other units, such as milliseconds or nanoseconds
Do note, however, that secondsElapsed
is not guaranteed to be positive unless the is_steady
member of the clock is true
because that member being true
means that a subsequent call to now()
will give a larger number than a former call to now()
.
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