使用tv_usec或tv_nsec的[milli|micro|nano]秒粒度
[ milli | micro | nano ]second granularity using tv_usec or tv_nsec
我正在做一个项目,我需要比整秒(即时间())更精细的粒度。我浏览了opengroup.org,注意到有一些带有member tv_usec和tv_nsec的数据结构。
#include <stdio.h>
#include <time.h>
int main (void) {
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
printf("%lis %linsn", 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
有没有一种简单的方法可以通过使用标准库来获得高精度的时间值?我实际上并不需要高精度,但我确实需要相对时间的增量。
在C++11中,#include <chrono>
并使用std::chrono::high_resolution_clock
(也可从Boost获得)。
在Posix中,您可以使用gettimeofday
来获得微秒时间戳,或者使用clock_gettime
来获得纳秒分辨率。
看看我为评测编写的以下代码。在那里,您将发现在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";
}
感谢所有给出答案的人,以下是与LINUX/UNIX相当的Windows答案。。。
#include <stdio.h>
#include <windows.h>
int main (void) {
SYSTEMTIME st;
GetSystemTime(&st);
printf("%lis %linsn", st.wSecond, st.wMilliseconds);
return 0;
}
编辑:您可能还想检查GetTickCount(),但我认为它需要花费CPU。