Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternatives to <ctime>

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.

like image 408
Tux Avatar asked Nov 15 '12 02:11

Tux


1 Answers

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

like image 131
chris Avatar answered Oct 14 '22 03:10

chris