[英]Are clock_gettime() in C++ and time.time() in python equivalent?
[英]c++ time.h, clock_gettime(), semantic error, how to link real-time library in Eclipse?
使用clock_gettime()函數時遇到一些問題。
#include <iostream>
#include <time.h>
timespec timer_start;
timespec timer_end;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &timer_start);
// sleep for 5 seconds
boost::this_thread::sleep(boost::posix_time::milliseconds(5000));
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &timer_end);
std::cout << (timer_end.tv_sec - timer_start.tv_sec) << ":" << (timer_end.tv_nsec - timer_start.tv_nsec) << std::endl;
我得到的輸出是這個
0:6934599
似乎計時器僅經過693毫秒左右。
我在Linux gnu gcc 4.6上使用g ++ -lrt編譯程序。 我還收到語義錯誤,提示無法解析符號“ CLOCK_PROCESS_CPUTIME_ID”
謝謝。
除了運行程序無法編譯失敗的可能性外,睡眠通常是系統調用:調用內核函數,內核將線程發送到睡眠狀態,安排其他線程和進程運行(或CPU進入節能狀態)模式),並在請求的時間再次喚醒原始線程。 在這段時間內,休眠線程不會占用CPU時間。 經過的(實際)時間通常稱為牆時間 。
與此相比,您的代碼中的實時等待 while
循環會反復檢查時鍾,並且僅在5秒鍾后終止。 這種等待會占用更多其他進程的CPU時間。
另請注意,6934599納秒約為6.93毫秒,而不是693。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.