【问题标题】:Definitive function for get elapsed time in miliseconds以毫秒为单位获取经过时间的权威函数
【发布时间】:2010-06-29 08:50:55
【问题描述】:

我试过clock_gettime(CLOCK_REALTIME)gettimeofday() 都没有运气 - 而最基本的,比如clock(),什么返回0给我(?)。

但他们都没有计算睡眠时间。我不需要高分辨率计时器,但我需要一些东西来获取以毫秒为单位的经过时间。

编辑:最终程序:

#include <iostream>
#include <string>
#include <time.h>
#include <sys/time.h>
#include <sys/resource.h>

using namespace std;

// Non-system sleep (wasting cpu)
void wait ( int seconds )
{
  clock_t endwait;
  endwait = clock () + seconds * CLOCKS_PER_SEC ;
  while (clock() < endwait) {}
}

int show_time() {
    timeval tv;
    gettimeofday(&tv, 0);
    time_t t = tv.tv_sec;
    long sub_sec = tv.tv_usec;

    cout<<"t value: "<<t<<endl;
    cout<<"sub_sec value: "<<sub_sec<<endl;
}

int main() {
    cout<<show_time()<<endl;
    sleep(2);
    cout<<show_time()<<endl;
    wait(2);
    cout<<show_time()<<endl;
}

【问题讨论】:

    标签: c++ time


    【解决方案1】:

    你需要再次尝试gettimeofday(),它肯定会计算挂钟时间,所以它也会在进程休眠时计算。

    long long getmsofday()
    {
       struct timeval tv;
       gettimeofday(&tv);
       return (long long)tv.tv_sec*1000 + tv.tv_usec/1000;
    }
    
    
    ...
    
    long long start = getmsofday();
    do_something();
    long long end = getmsofday();
    
    printf("do_something took %lld ms\n",end - start);
    

    【讨论】:

    • 值得注意的是gettimeofday需要
    • 我已经重新检查过了,我已经让它与 gettimeofday 完美配合!我想我做错了什么......我会用我的最终测试程序更新这个问题。谢谢!
    • 应该是tv.tv_sec*1000 + ..
    【解决方案2】:

    您的问题可能与积分除法有关。您需要将一个除法操作数转换为浮点数/双精度数,以避免在不到一秒的时间内截断十进制值。

    clock_t start = clock();
    // do stuff
    
    // Can cast either operand for the division result to a double.
    // I chose the right-hand operand, CLOCKS_PER_SEC.
    double time_passed = clock() / static_cast<double>(CLOCKS_PER_SEC);
    

    [编辑] 正如所指出的,clock() 测量 CPU 时间(时钟滴答/周期),不适合用于挂钟测试。如果你想要一个可移植的解决方案,@see Boost.Timer 作为一个可能的解决方案

    【讨论】:

      【解决方案3】:

      你实际上想要clock_gettime(CLOCK_MONOTONIC, ...)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-19
        • 2012-11-15
        • 2013-05-26
        • 2017-08-05
        • 2013-05-09
        相关资源
        最近更新 更多