C/C++ 計算算法的執行時間


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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM