Is there a standard library equivalent of timeGetTime()?

落爺英雄遲暮 提交于 2020-01-16 13:16:21

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!