如何使用 C++ 中的 clock() 函式
我們將在這裡瞭解如何在 C++ 中使用 clock()。此 clock() 存在於 time.h 或 ctime 標頭檔案中。我們將在其中使用此 clock() 函式找到程序的消耗時間
若要獲得消耗時間,我們可以在開始時和任務結束時使用 clock() 來獲得時間,然後減去這些值以獲取差異。之後,我們將差異除以 CLOCK_PER_SEC(每秒鐘週期數)以獲取處理器時間。
示例
#include <iostream>
#include <ctime>
using namespace std;
void take_enter() {
cout << "Press enter to stop the counter" <<endl;
while(1) {
if (getchar())
break;
}
}
main() {
// Calculate the time taken by take_enter()
clock_t t;
t = clock();
cout << "Timer starts\n";
take_enter();
cout << "Timer ends \n";
t = clock() - t;
double time_taken = ((double)t)/CLOCKS_PER_SEC; // calculate the elapsed time
cout << "The program took "<< time_taken <<" seconds to execute";
}輸出
Timer starts Press enter to stop the counter Timer ends The program took 3.546 seconds to execute
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP