C/C++ 計算演算法的執行時間
阿新 • • 發佈:2021-12-06
C/C++中,計算演算法時間方法各異,不同系統平臺提供系統呼叫介面可能不一樣。
使用clock()
clock()獲取從程式啟動到呼叫時,CPU計時時間,精度CLOCKS_PER_SEC。
CLOCKS_PER_SEC也是每個CPU計數所代表的時間含義,比如CLOCKS_PER_SEC為1000,代表CPU每秒鐘計數1000,即這段時間對應“時鐘脈衝數”,clock() / CLOCKS_PER_SEC 就是這段時間的秒數。
遵循標準
POSIX.1-2001, POSIX.1-2008, C89, C99. XSI requires that
CLOCKS_PER_SEC equals 1000000 independent of the actual
resolution.
函式詳解參見 man 3 clock手冊
下面3個測試用例,分別讓程序休眠2s,20ms,20us,然後統計程序執行時間。
#include <time.h> #include <thread> using namespace std; using namespace std::this_thread::sleep_for; void test_clock1() { clock_t start = clock(); sleep_for(chrono::seconds(2)); // 休眠2s clock_t end = clock(); cout << double(start - end) / CLOCKS_PER_SEC << "s" << endl; // 列印2s } void test_clock2() { clock_t start = clock(); sleep_for(chrono::milliseconds(20)); // 休眠20ms clock_t end = clock(); cout << double(start - end) / CLOCKS_PER_SEC << "s" << endl; // 列印0.02s } void test_clock3() { // 測試用例3 clock_t start = clock(); sleep_for(chrono::microseconds(20)); // 休眠20us clock_t end = clock(); cout << double(start - end) / CLOCKS_PER_SEC << "s" << endl; // 列印0.001s }
可以看出,使用clock()方式無法獲取 <= 1ms的時間。這是因為測試機上CLOCKS_PER_SEC=1000,也就是該計數器每秒計數1000次(時鐘脈衝)。
使用time()
time() 返回自UTC時間(1970-01-01 00:00:00 +0000 (UTC))以來的秒數。精度為1秒。
遵循標準
SVr4, 4.3BSD, C89, C99, POSIX.1-2001. POSIX does not specify any
error conditions.
函式詳見man 2 time手冊
下面3個測試用例,分別讓程序休眠2s,20ms,20us,然後統計程序執行時間。
void test_time1() { time_t start = time(NULL); sleep_for(chrono::seconds(2)); // 列印2秒 time_t end = time(NULL); cout << end - start << "s" << endl; } void test_time2() { time_t start = time(NULL); sleep_for(chrono::milliseconds(20)); // 列印0秒 time_t end = time(NULL); cout << end - start << "s" << endl; } void test_time3() { time_t start = time(NULL); sleep_for(chrono::microseconds(20)); // 列印0秒 time_t end = time(NULL); cout << end - start << "s" << endl; }