簡體   English   中英

C ++准確的計時器time.h boost :: posix_time

[英]c++ accurate timer time.h boost::posix_time

我正在嘗試創建一個計時器來分析某些功能。 例如,

#include <date_time/posix_time/posix_time.hpp>

boost::posix_time::ptime t1, t2;
t1 = boost::posix_time::microsec_clock::local_time();
boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
t2 = boost::posix_time::microsec_clock::local_time();

std::cout << to_simple_string(t1) << std::endl;
std::cout << to_simple_string(t2) << std::endl;

我得到的輸出是這樣,

2012-Mar-04 08:21:24.760019
2012-Mar-04 08:21:25.760577

實際經過的時間是1秒和558微秒,反正我可以提高這種精度,比如說在1微秒以下嗎?

我也使用鏈接器-lrt嘗試了類似的方法。

#include <time.h>
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &timer_start);
boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
clock_gettime(1CLOCK_PROCESS_CPUTIME_ID, &timer_end);

但是編譯器返回CLOCK_PROCESS_CPUTIME_ID的語義錯誤。 錯誤消息如下。

Description Resource    Path    Location    Type
Symbol 'CLOCK_PROCESS_CPUTIME_ID' could not be resolved _OVERVIEW.cpp   /FUTETP/BACKEND line 32 Semantic Error

請記住兩件事:

  1. 由於多種原因(系統負載等), sleep()和其他對時間敏感的命令可能不准確。 您將永遠無法獲得1微秒的精度。 500毫秒對於計時sleep()來說還不錯
  2. 如果您的系統時間是由NTP等控制的,並且在計時操作期間更改了時鍾, 則會看到此信息。 如果時間回滾,則有可能獲得負數(或較大的無符號數)。

順便說一句,我不確定Boost正在使用哪種方法獲取時間,但是請考慮從sys/time.h (或從time.h更新的clock_gettime()獲取gettimeofday(2) )。 它返回從1970年1月1日午夜開始的時間。記錄前后的時間並減去。 這是gettimeofday()的示例。

#include <sys/time.h>

#include <stdio.h>
#include <unistd.h>

unsigned int
timeDif(
    struct timeval *before,
    struct timeval *after)
{
    return ((after->tv_sec * 1000000 + after->tv_usec) - 
        (before->tv_sec * 1000000 + before->tv_usec));
}

int
main(
    int argc,
    char *argv[]) {
    struct timeval before, after;

    gettimeofday(&before, NULL);
    sleep(1);
    gettimeofday(&after, NULL);

    printf("Elapsed time: %u microseconds\n", timeDif(&before, &after));

    return (0);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM