參照Obtaining Time in milliseconds獲取在納秒
時差爲什麼以下代碼產生零作爲輸出?
int main()
{
steady_clock::time_point t1 = steady_clock::now();
//std::this_thread::sleep_for(std::chrono::milliseconds(1500));
steady_clock::time_point t2 = steady_clock::now();
auto timeC = t1.time_since_epoch().count();
auto timeD = t2.time_since_epoch().count();
auto timeA = duration_cast<std::chrono::nanoseconds > (t1.time_since_epoch()).count();
auto timeB = duration_cast<std::chrono::nanoseconds > (t2.time_since_epoch()).count();
std::cout << timeC << std::endl;
std::cout << timeB << std::endl;
std::cout << timeD << std::endl;
std::cout << timeA << std::endl;
std::cout << timeB - timeA << std::endl;
system("Pause");
return 0;
}
輸出:
14374083030139686
1437408303013968600
14374083030139686
1437408303013968600
0
Press any key to continue . . .
我想應該是因爲指令執行時間幾納秒的差異。
你的滴答不像納秒,因此滴答計數不能以納秒精度表示。一定?觀察時鐘的「週期」來驗證。你不能獲得比時鐘週期更好的精度。 –
即使以毫秒爲單位,它也會產生結果爲零 –
那麼,您的代碼不會太多,所以這也不足爲奇。如果你重新加入睡眠怎麼辦? –