我們可以通過 時間度量 - Wall time vs. CPU time 來知道Wall time和CPU time的區別是什麼,簡單來講,Wall Time就是類似我們的時鐘一樣,他沒有很精確的表示此時CPU花了多少時間,而是直接用了比較粗的方式去統計。而CPU Time就比較精確的告訴了我們,CPU在執行這段指令的時候,一定消耗了多少時間。接下來我們將簡單介紹8種方式來進行程序計時
如果你本身的測試程序是一個高密度的計算,比如while (10000) 內部瘋狂做計算,那麼你的CPU占用肯定是100%,這種情況下,你的wall time和你的CPU time其實很難區分。在這種情況下,如果你想讓你的CPU IDLE一會的話,你可以簡單的通過sleep()就可以進行實現,因為CPU在sleep()狀態下是IDLE的。
1.time命令 - for Linux(Windows沒有找到合適的替代品), Wall Time + CPU Time, seconds
你可以直接time你的program, 而且不需要修改你的代碼,當你的程序結束運行,對應的結果會刷出來,他會同時包含wall time以及CPU time
上面的real表示wall time, user表示CPU time.同時你不需要修改你的代碼。
2.#include <chrono> - for Linux & Windows(需要C++ 11),Wall Time, nanoseconds
他是度量wall time的最合適和可移植性的方法。chrono擁有你機器中的不同的clocks, 每個clock都有各自不同的目的和特徵。當然除非你有特殊的要求,一般情況下你只需要high_resolution_clock.他擁有最高精度的CLOCK,本身也應該比較實用
#include <stdio.h>
#include <chrono>
int main () {
double sum = 0;
double add = 1;
// Start measuring time
auto begin = std::chrono::high_resolution_clock::now();
int iterations = 1000*1000*1000;
for (int i=0; i<iterations; i++) {
sum += add;
add /= 2.0;
}
// Stop measuring time and calculate the elapsed time
auto end = std::chrono::high_resolution_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin);
printf("Result: %.20f\n", sum);
printf("Time measured: %.3f seconds.\n", elapsed.count() * 1e-9);
return 0;
}
可以看到,通過duration_cast我們可以把時間轉換到nanoseconds,除此之外,還支持hours, minutes, seconds, millseconds, microseconds。同時需要注意的是,使用chrono庫可能會比其他的C/C++方法需要損失的性能更高,尤其是在一個loop執行多次。
3.#include <sys/time.h> gettimeofday() - for Linux & Windows, Wall time,microseconds
這個函數會返回從00:00:00 UTC(1970 1.1) Epoch time. 比較tricky的一點是,這個函數會同時返回 seconds以及microseconds在不同的分別的long int變量里。所以,如果你想獲取總的時間包括microseconds,你需要手動對他們做sum()
#include <stdio.h>
#include <sys/time.h>
int main () {
double sum = 0;
double add = 1;
// Start measuring time
struct timeval begin, end;
gettimeofday(&begin, 0);
int iterations = 1000*1000*1000;
for (int i=0; i<iterations; i++) {
sum += add;
add /= 2.0;
}
// Stop measuring time and calculate the elapsed time
gettimeofday(&end, 0);
long seconds = end.tv_sec - begin.tv_sec;
long microseconds = end.tv_usec - begin.tv_usec;
double elapsed = seconds + microseconds*1e-6;
printf("Result: %.20f\n", sum);
printf("Time measured: %.3f seconds.\n", elapsed);
return 0;
}
- 如果你對小數點不感冒,你可以直接通過end.tv_sec - begin.tv_sec來獲取秒級單位
- 第二個參數是用來設置當前的timezone.由於我們計算的是elapsed time, 因此timezone就沒有關係
4.#include <time.h> time() - for Linux & Windows, Wall time, seconds
time()跟第三條的gettimeofday()類似,他會基於Epoch time。但是又跟gettimeofday()有兩個比較大的區別:
- 你不能像gettimeofday()一樣在第二個參數設置timezone,所以他始終是UTC
- 他始終只會返回full seconds
因此因為上面的第二點原因,除非你的測量精度就是seconds,否則意義不大
#include <stdio.h>
#include <time.h>
int main () {
double sum = 0;
double add = 1;
// Start measuring time
time_t begin, end;
time(&begin);
int iterations = 1000*1000*1000;
for (int i=0; i<iterations; i++) {
sum += add;
add /= 2.0;
}
// Stop measuring time and calculate the elapsed time
time(&end);
time_t elapsed = end - begin;
printf("Result: %.20f\n", sum);
printf("Time measured: %ld seconds.\n", elapsed);
return 0;
}
time_t實際上就是alias long int,因此你可以直接用printf()和cout進行列印
5.#include <time.h> clock() - for Linux & Windows, CPU time on Linux, Wall time on Windows, seconds
clock()會返回在程序開始執行之後的clock ticks. 你可以通過他去除以CLOCKS_PER_SEC(在自己的Linux虛擬機測下來這個值是1000000),你會得到程序執行了多少時間(s).但是這對於不同的作業系統,行為是不一樣的,比如在Linux,你得到的是CPU time,在Windows,你得到的是Wall time.因此你需要特別小心
#include <stdio.h>
#include <time.h>
int main () {
double sum = 0;
double add = 1;
// Start measuring time
clock_t start = clock();
int iterations = 1000*1000*1000;
for (int i=0; i<iterations; i++) {
sum += add;
add /= 2.0;
}
// Stop measuring time and calculate the elapsed time
clock_t end = clock();
double elapsed = double(end - start)/CLOCKS_PER_SEC;
printf("Result: %.20f\n", sum);
printf("Time measured: %.3f seconds.\n", elapsed);
return 0;
}
clock_t本身也是long int, 所以當你用除法去除以CLOCKS_PER_SEC的時候,你需要先轉換到double,否則你會因為整除而失去信息
6.#include <time.h> clock_gettime() - for Linux Only, Wall time / CPU time,nanoseconds
這個API是比較強大的,因為他既可以用來測Wall time又可以用來測CPU time,同時他支持nanoseconds級別。但是他唯一的不好的地方就是他只適用於Unix.你可以通過flag來控制測量wall time或者是CPU time,通過對應的CLOCK_PROCESS_CPUTIME_ID(wall time)或者CLOCK_REALTIME(CPU time)
#include <stdio.h>
#include <time.h>
int main () {
double sum = 0;
double add = 1;
// Start measuring time
struct timespec begin, end;
clock_gettime(CLOCK_REALTIME, &begin);
int iterations = 1000*1000*1000;
for (int i=0; i<iterations; i++) {
sum += add;
add /= 2.0;
}
// Stop measuring time and calculate the elapsed time
clock_gettime(CLOCK_REALTIME, &end);
long seconds = end.tv_sec - begin.tv_sec;
long nanoseconds = end.tv_nsec - begin.tv_nsec;
double elapsed = seconds + nanoseconds*1e-9;
printf("Result: %.20f\n", sum);
printf("Time measured: %.3f seconds.\n", elapsed);
return 0;
}
除了CLOCK_REALTIME和CLOCK_PROCESS_CPUTIME_ID之外,你可以使用其他的clock types. 這裡的timespec跟gettimeofday()的timeval很類似,但是timeval包含的是microseconds,而timespec包含的是nanoseconds
7.#include <sysinfoapi.h> GetTickCount64() - for Windows Only, milliseconds
返回當系統開機之後的millseconds毫秒個數,同樣這裡也有32位的版本GetTickCount(), 但是他會把時間限制在49.71 days,所以用64 bit都是比較好的
#include <stdio.h>
#include <sysinfoapi.h>
int main () {
double sum = 0;
double add = 1;
// Start measuring time
long long int begin = GetTickCount64();
int iterations = 1000*1000*1000;
for (int i=0; i<iterations; i++) {
sum += add;
add /= 2.0;
}
// Stop measuring time and calculate the elapsed time
long long int end = GetTickCount64();
double elapsed = (end - begin)*1e-3;
printf("Result: %.20f\n", sum);
printf("Time measured: %.3f seconds.\n", elapsed);
return 0;
}
8.#include <processthreadsapi.h> GetProcessTimes() - for Windows Only(但是這時唯一可以在Windows上測量CPU time的方法), CPU time
原理本身比較複雜,如果有興趣可以自己找資料繼續閱讀
#include <stdio.h>
#include <processthreadsapi.h>
double get_cpu_time(){
FILETIME a,b,c,d;
if (GetProcessTimes(GetCurrentProcess(),&a,&b,&c,&d) != 0){
// Returns total user time.
// Can be tweaked to include kernel times as well.
return
(double)(d.dwLowDateTime |
((unsigned long long)d.dwHighDateTime << 32)) * 0.0000001;
}else{
// Handle error
return 0;
}
}
int main () {
double sum = 0;
double add = 1;
// Start measuring time
double begin = get_cpu_time();
int iterations = 1000*1000*1000;
for (int i=0; i<iterations; i++) {
sum += add;
add /= 2.0;
}
// Stop measuring time and calculate the elapsed time
double end = get_cpu_time();
double elapsed = (end - begin);
printf("Result: %.20f\n", sum);
printf("Time measured: %.3f seconds.\n", elapsed);
return 0;
}
網上有人基於這個工具提供了同時計算CPU time以及wall time的方法, 有興趣的話可以自己去進行進一步學習