如何使用 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