[milli |微|使用tv_usec或tv_nsec的nano]第二粒度

时间:2012-07-20 22:55:09

标签: c++

我正在处理一个项目,我需要一个比整秒更精细的粒度(即time())。我正在浏览opengroup.org,我注意到有数据结构与成员tv_usec和tv_nsec。

#include <stdio.h>
#include <time.h>

int main (void) {
      struct timespec ts;
      clock_gettime(CLOCK_REALTIME, &ts);
      printf("%lis %lins\n", ts.tv_sec, ts.tv_nsec);

      return 0;
}


test.cpp(5) : error C2079: 'ts' uses undefined struct 'main::timespec'
test.cpp(6) : error C2065: 'CLOCK_REALTIME' : undeclared identifier
test.cpp(6) : error C3861: 'clock_gettime': identifier not found

使用标准库是否有一种简单的方法来获得高精度的时间值?我实际上并不需要高精度,但我确实需要增加相对时间。

3 个答案:

答案 0 :(得分:5)

在C ++ 11中,#include <chrono>并使用std::chrono::high_resolution_clock(也可从Boost获得)。

在Posix中,您可以使用gettimeofday获取微秒时间戳,或clock_gettime获得纳秒级分辨率。

答案 1 :(得分:1)

看看我为分析编写的以下代码。在那里你会发现在linux环境中调用ns时间戳。对于其他环境,您可能需要替换CLOCK_MONOTONIC

#ifndef PROFILER_H
#define PROFILER_H

#include <sys/time.h>
#include <QString>

class Profiler
{
  public:
    Profiler(QString const& name);
    long measure() const;

    long measureNs() const;
    double measureMs() const;
    double measureS() const;
    void printNs() const;
    void printMs() const;
    void printS() const;
  private:
    QString mName;
    timespec mTime;
};

#endif // PROFILER_H

#include "profiler.h"
#include <QDebug>
#include <assert.h>
#include <iostream>

Profiler::Profiler(QString const& name):mName(name){
  clock_gettime(CLOCK_MONOTONIC, &mTime); // Works on Linux
}


long int Profiler::measureNs() const{
  timespec end;
  clock_gettime(CLOCK_MONOTONIC, &end); // Works on Linux 
  long int diff = (end.tv_sec-mTime.tv_sec) * 1000000000 + (end.tv_nsec - mTime.tv_nsec);
  assert(diff>0);
  return diff;
}

double Profiler::measureMs() const{
  return measureNs()/1000000.0;
}

double Profiler::measureS() const{
  return measureMs()/1000.0;
}

void Profiler::printNs() const{
  qDebug() << mName << "Time elapsed:" << measureNs() << "ns";
}

void Profiler::printMs() const{
  qDebug() << mName << "Time elapsed:" << measureMs() << "ms";
}

void Profiler::printS() const{
  qDebug() << mName << "Time elapsed:" << measureS() << "S";
}

答案 2 :(得分:1)

感谢所有给出答案的人,这里是Windows等效的LINUX / UNIX答案......

#include <stdio.h>
#include <windows.h>

int main (void) {
SYSTEMTIME st;
GetSystemTime(&st);
printf("%lis %lins\n", st.wSecond, st.wMilliseconds);

return 0;
}

编辑:您可能还想检查GetTickCount(),但我认为这是以CPU成本为准。

相关问题