C++ のコードの一部の実行時間 (MS) をどのように計算しますか?
3 に答える
ほとんどのシステムは、高性能のタイミングメカニズムをサポートしています。Windowsでは、高性能タイマーAPIを使用できます。
* nixシステムでは、を使用できますclock_getres() and clock_gettime()
。
これらを使用してコードの時間を計る方法を理解できるはずです。
移植可能なコードでできる最善のことは、clock()
.
clock_t start = clock();
// code to time goes here
clock_t stop = clock();
double seconds = double(stop-start)/CLOCKS_PER_SEC;
C++11 では、<chrono>
クラス fortime_point
およびという名前の新しいヘッダーが追加されduration
、ジョブがよりシンプルでクリーンになります。ただし、これらのいずれもミリ秒レベルの精度 (または精度) を保証するものではありません。新しいクラスには、ナノ秒の範囲までの期間の typedef がありますが、実際の結果が正確であるかどうかについての保証はありません (ただし、ほとんどの典型的な OS では、答えは通常「そうではない」と確信しています)。
これは私がc ++(11ではない)に使用するものですが、多くのライブラリにはより精巧なソリューションがあるかもしれません. コードにはQtが必要ですが、Qtがなくても簡単に実行できます。オペレーティング システムによっては、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";
}
使用法:
Profiler pro("Tag you want");
function();
pro.printMs();