问题
I've tried search without really finding an answer to this question that meets me requirements or explains it clearly enough.
I'm looking for a function or a way to implement a function that can retrieve the number of ticks or milliseconds in the same way that the timeGetTime() function does in windows.
I'm looking for a solution that only uses standard C++, no additional libraries or platform specifics (like timeGetTime() on windows or a linux equivalent; a multi-platform solution).
I'm trying to keep my code platform independent at the lower level of the library and I just want to know if anyone can tell me/point me to the way to put something together similar to timeGetTime().
Thanks
Update: I'm not necessarily looking for high performance and accuracy, I only need millisecond precision to see how much time has elapsed since I last checked.
回答1:
You can use the ever so verbose <chrono> library added in C++11.
It has different types of clocks depending on what you want, with system_clock
being the only one that can be used with time_t
and high_resolution_clock
being the one with the smallest tick possible.
Timing things is relatively simple with it, for example:
#include <iostream>
#include <chrono>
int main() {
auto now = std::chrono::high_resolution_clock::now();
//do stuff here
auto then = std::chrono::high_resolution_clock::now();
std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(then-now).count();
}
回答2:
C++11 added header <chrono>
which provides a standardized way to read the system time with higher resolution than the old localtime
. Accuracy varies wildly by platform, however.
The steady_clock
class will probably be most useful to you.
来源:https://stackoverflow.com/questions/14783468/is-there-a-standard-library-equivalent-of-timegettime