C ++で時差を計算する最良の方法は何ですか?プログラムの実行速度を計っているので、ミリ秒に興味があります。さらに良いのは、seconds.milliseconds ..
受け入れられた回答は機能しますが、コメントに記載されているようにctimeまたはtime.hを含める必要があります。
C ++で時差を計算する最良の方法は何ですか?プログラムの実行速度を計っているので、ミリ秒に興味があります。さらに良いのは、seconds.milliseconds ..
受け入れられた回答は機能しますが、コメントに記載されているようにctimeまたはtime.hを含める必要があります。
回答:
std::clock()関数を参照してください。
const clock_t begin_time = clock();
// do something
std::cout << float( clock () - begin_time ) / CLOCKS_PER_SEC;
(ユーザーではなく)自己の実行時間を計算する場合は、これを(秒ではなく)クロック刻みで計算することをお勧めします。
編集:
責任あるヘッダーファイル- <ctime>または<time.h>
clock()プログラムが消費したCPU時間を返します。したがって、プログラムが並行して実行される場合、関数によって返される時間は、経過時間ではなく、すべてのCPUで費やされた時間の累積になります cplusplus.com/reference/ctime/clock
c ++ 11を使用している場合、簡単なラッパーを次に示します(この要点を参照)。
#include <iostream>
#include <chrono>
class Timer
{
public:
Timer() : beg_(clock_::now()) {}
void reset() { beg_ = clock_::now(); }
double elapsed() const {
return std::chrono::duration_cast<second_>
(clock_::now() - beg_).count(); }
private:
typedef std::chrono::high_resolution_clock clock_;
typedef std::chrono::duration<double, std::ratio<1> > second_;
std::chrono::time_point<clock_> beg_;
};
または* nixのc ++ 03の場合:
#include <iostream>
#include <ctime>
class Timer
{
public:
Timer() { clock_gettime(CLOCK_REALTIME, &beg_); }
double elapsed() {
clock_gettime(CLOCK_REALTIME, &end_);
return end_.tv_sec - beg_.tv_sec +
(end_.tv_nsec - beg_.tv_nsec) / 1000000000.;
}
void reset() { clock_gettime(CLOCK_REALTIME, &beg_); }
private:
timespec beg_, end_;
};
使用例:
int main()
{
Timer tmr;
double t = tmr.elapsed();
std::cout << t << std::endl;
tmr.reset();
t = tmr.elapsed();
std::cout << t << std::endl;
return 0;
}
Timer()とelapsed()if の呼び出しの間の時間を変更した場合には機能しません。これは!std::chrono::high_resolution_clock::is_steadyLinuxの場合です。
Boost、特にboost :: posix_time :: ptimeとboost :: posix_time :: time_duration(http://www.boost.org/doc/libs/1_38_0/doc/html/date_time/posix_time)の使用を真剣に検討する.html)。
クロスプラットフォームで使いやすく、私の経験では、オペレーティングシステムが提供する最高レベルの時間分解能を提供します。おそらく非常に重要です。それはいくつかの非常に素晴らしいIO演算子を提供します。
これを使用してプログラム実行の差(マイクロ秒まで;おそらくやり過ぎ)を計算するには、次のようになります[ブラウザーは記述されており、テストされていません]:
ptime time_start(microsec_clock::local_time());
//... execution goes here ...
ptime time_end(microsec_clock::local_time());
time_duration duration(time_end - time_start);
cout << duration << '\n';
この回答を追加して、受け入れられた回答が希望する時間ではない可能性があるCPU時間を示していることを明確にしました。参考資料によると、CPU時間と実時間があります。実時間は、他のプロセスで共有されているCPUなどの他の条件に関係なく、実際の経過時間を示す時間です。たとえば、特定のタスクを実行するために複数のプロセッサを使用していて、CPU時間は18秒と高かったため、実際の実時間では2秒かかりました。
実際の時間を取得するには、
#include <chrono>
auto t_start = std::chrono::high_resolution_clock::now();
// the work...
auto t_end = std::chrono::high_resolution_clock::now();
double elapsed_time_ms = std::chrono::duration<double, std::milli>(t_end-t_start).count();
ブースト1.46.0以降には、Chronoライブラリが含まれています。
thread_clockクラスは、実際のスレッドの壁時計、つまり呼び出し側スレッドの実際のCPU時間クロックへのアクセスを提供します。スレッドの相対的な現在時刻は、thread_clock :: now()を呼び出すことで取得できます。
#include <boost/chrono/thread_clock.hpp>
{
...
using namespace boost::chrono;
thread_clock::time_point start = thread_clock::now();
...
thread_clock::time_point stop = thread_clock::now();
std::cout << "duration: " << duration_cast<milliseconds>(stop - start).count() << " ms\n";
std::chronoほぼ同じ内容の名前空間があります。
Windowsの場合:GetTickCountを使用します
//GetTickCount defintition
#include <windows.h>
int main()
{
DWORD dw1 = GetTickCount();
//Do something
DWORD dw2 = GetTickCount();
cout<<"Time difference is "<<(dw2-dw1)<<" milliSeconds"<<endl;
}
clock_gettimeを使用することもできます。この方法は、次の測定に使用できます。
コードは次のとおりです。
#include < time.h >
#include <iostream>
int main(){
timespec ts_beg, ts_end;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts_beg);
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts_end);
std::cout << (ts_end.tv_sec - ts_beg.tv_sec) + (ts_end.tv_nsec - ts_beg.tv_nsec) / 1e9 << " sec";
}
`
余談ですが、Windowsで実行していて本当に本当に精度が必要な場合は、QueryPerformanceCounterを使用できます。それはあなたに(潜在的に)ナノ秒で時間を与えます。
私にとって、最も簡単な方法は次のとおりです。
#include <boost/timer.hpp>
boost::timer t;
double duration;
t.restart();
/* DO SOMETHING HERE... */
duration = t.elapsed();
t.restart();
/* DO OTHER STUFF HERE... */
duration = t.elapsed();
このコードを使用すると、クラシックを実行する必要はありませんend - start。
あなたの好きなアプローチをお楽しみください。
最初にシステム時間をミリ秒単位で取得し、最後に再度取得して、減算します。
POSIXで1970年からのミリ秒数を取得するには、次のように記述します。
struct timeval tv;
gettimeofday(&tv, NULL);
return ((((unsigned long long)tv.tv_sec) * 1000) +
(((unsigned long long)tv.tv_usec) / 1000));
Windowsで1601以降のミリ秒数を取得するには、次のように記述します。
SYSTEMTIME systime;
FILETIME filetime;
GetSystemTime(&systime);
if (!SystemTimeToFileTime(&systime, &filetime))
return 0;
unsigned long long ns_since_1601;
ULARGE_INTEGER* ptr = (ULARGE_INTEGER*)&ns_since_1601;
// copy the result into the ULARGE_INTEGER; this is actually
// copying the result into the ns_since_1601 unsigned long long.
ptr->u.LowPart = filetime.dwLowDateTime;
ptr->u.HighPart = filetime.dwHighDateTime;
// Compute the number of milliseconds since 1601; we have to
// divide by 10,000, since the current value is the number of 100ns
// intervals since 1601, not ms.
return (ns_since_1601 / 10000);
1970年以降のミリ秒数も返すようにWindowsの回答を正規化する場合は、11644473600000ミリ秒だけ回答を調整する必要があります。しかし、あなたが気にしているのが経過時間だけなら、それは必要ではありません。