[英]How to get execution time of a piece of code in C++?
我正在嘗試對一段代碼進行基准測試。 正是基於這個代碼在這里有一個有趣的現象基本上看起來像這樣:
auto t0 = std::chrono::high_resolution_clock::now();
...
auto t1 = std::chrono::high_resolution_clock::now();
std::cout << secs(t1-t0).count() << " s\n";
問題是我在一台共享機器上,這給了我一些時間,所以我的結果並沒有給我任何一致性。 我真正需要的是某種秒表工具,它可以讓我得到我的代碼運行的時間,而不是牆上的時間。 有什么選擇? 如果涉及系統特定的調用,我在Linux機器上,但如果可能的話,我寧願保持這段代碼的可移植性。
如果在您的操作系統上可用,您可以使用時間API來獲得與內置time
命令類似的結果。
#include <sys/times.h>
...
struct tms start, end;
times(&start);
//Do command
times(&end);
clock_t usr_time = end->tms_utime - start->tms_utime;
clock_t sys_time = end->tms_stime - start->tms_stime;
要100%完成,您應檢查時間結果是否不等於-1
,否則請檢查errno
代碼。
理想情況下,正如您提到的問題中的注釋一樣,您應該將要測量的代碼段隔離在main
內部,並使用unix time
命令行工具,該工具報告user
和system
時間。
如果您無法做到這一點,請考慮查看源代碼的time
並可能使用相同的技術來對代碼進行基准測試。
我認為您需要將clock_gettime()
與以下時鍾CLOCK_PROCESS_CPUTIME_ID
或CLOCK_THREAD_CPUTIME_ID
。 它們給出進程/線程消耗的CPU時間量。
CLOCK_PROCESS_CPUTIME_ID
High-resolution per-process timer from the CPU.
CLOCK_THREAD_CPUTIME_ID
Thread-specific CPU-time clock.
參考:
我認為在許多情況下給出merlin2011
的建議是不可行的,因為隔離可能需要很多努力,而使用clock_gettime()
添加兩行代碼是非常實用的。 您甚至可以在類中包含對clock_gettime()
調用。
對於Linux
#include <time.h>
#include <stdio.h>
double theseSecs = 0.0;
double startSecs = 0.0;
double secs;
double CPUsecs = 0.0;
double CPUutilisation = 0.0;
double answer = 0;
clock_t starts;
void start_CPU_time()
{
starts = clock();;
return;
}
void end_CPU_time()
{
CPUsecs = (double)(clock() - starts)/(double)CLOCKS_PER_SEC;
return;
}
struct timespec tp1;
void getSecs()
{
clock_gettime(CLOCK_REALTIME, &tp1);
theseSecs = tp1.tv_sec + tp1.tv_nsec / 1e9;
return;
}
void start_time()
{
getSecs();
startSecs = theseSecs;
return;
}
void end_time()
{
getSecs();
secs = theseSecs - startSecs;
return;
}
void calculate()
{
int i, j;
for (i=1; i<100001; i++)
{
for (j=1; j<10001; j++)
{
answer = answer + (float)i / 100000000.0;
}
}
}
void main()
{
start_time();
start_CPU_time();
calculate();
end_time();
end_CPU_time();
CPUutilisation = CPUsecs / secs * 100.0;
printf("\n Answer %10.1f, Elapsed Time %7.4f, CPU Time %7.4f, CPU Ut %3.0f%\n",
answer, secs, CPUsecs, CPUutilisation);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.