用于获取以毫秒为单位的经过时间的定义函数 [英] Definitive function for get elapsed time in miliseconds

查看:247
本文介绍了用于获取以毫秒为单位的经过时间的定义函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试过 clock_gettime(CLOCK_REALTIME) gettimeofday() c $ c> clock(),什么返回0给我(?)。

I have tried clock_gettime(CLOCK_REALTIME) and gettimeofday() without luck - And the most basic like clock(), what return 0 to me (?).

我不需要一个高分辨率的定时器,但我需要一些东西来获得经过的时间以毫秒为单位。

But none of they count the time under sleep. I don't need a high resolution timer, but I need something for getting the elapsed time in ms.

编辑:最终节目:

#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 $ c> gettimeofday(),它肯定会计算挂钟时间,所以它会计算进程休眠的时间。

You need to try gettimeofday() again, it certainly count the wall clock time, so it counts when the process sleep as well.

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);

这篇关于用于获取以毫秒为单位的经过时间的定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆