2012-07-20 321 views
2

我正在研究一个项目,我需要比整个秒(即time())更精细的粒度。我正在浏览opengroup.org,我注意到有数据结构与成员tv_usec和tv_nsec。[milli |微| |纳秒]粒度使用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 

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

+0

你正在使用什么操作系统? – 2012-07-20 22:57:39

+0

在这里编译...这是POSIX系统..你使用Windows或其他东西? – 2012-07-20 23:03:34

+0

是的,不幸的是我使用Windows ... – Zak 2012-07-21 01:51:22

回答

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的成本。

5

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

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

+1

[Boost.Chrono](http://www.boost.org/libs/chrono/)。 – Xeo 2012-07-20 23:03:33

+0

@Xeo:谢谢 - 更新! – 2012-07-20 23:06:22

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"; 
}