|
很多場合會需要進行運算時間的量測,而傳統的 clock 在時間精度上卻相當悲劇,在 15ms 內的時間幾乎很難正確評估。C++ 提供了一個方法,能讓時間量測變得相當精準。 |
|---|
std::chrono::high_resolution_clock
C++ 的 chrono 提供了一個方法,std::chrono::high_resolution_clock,其中包含了類別宣告 time_point,方法 now(),並且透過 std::chrono::duration 作為差異的銜接。底下為使用範例:
Sample
#include <chrono>
#include <iostream>
#include <thread>
int main(int argc, char* argv[])
{
std::chrono::high_resolution_clock::time_point t;
std::chrono::duration<double, std::milli> duration;
t = std::chrono::high_resolution_clock::now();
std::this_thread::sleep_for(std::chrono::milliseconds(10));
duration = std::chrono::high_resolution_clock::now() - t;
printf("This take %f ms.\n", duration.count());
system("pause");
}
程式執行應該會跑出下面的結果:
This take 15.743700 ms.
No comments:
Post a Comment