我该如何在 C++
中调用 clock()
函数?
例如,我想测试线性查找在一个数组中找到给定元素所需的时间。
我该如何在 C++
中调用 clock()
函数?
例如,我想测试线性查找在一个数组中找到给定元素所需的时间。
#include <iostream>
#include <cstdio>
#include <ctime>
int main() {
std::clock_t start;
double duration;
start = std::clock();
/* Your algorithm here */
duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
std::cout<<"printf: "<< duration <<'\n';
}
clock()
和clock_t
都来自于C标准库的time.h
头文件,因此在包含它们的库后不需要使用std
命名空间前缀。 <ctime>
将该值和函数与std
命名空间一起封装,但不需要使用。请在此处查看实现细节:http://en.cppreference.com/w/cpp/header/ctime - kayleeFrye_onDeck自 C++11 开始,一种可移植且精度更高的替代方案是使用 std::chrono
。
以下是一个示例:
#include <iostream>
#include <chrono>
typedef std::chrono::high_resolution_clock Clock;
int main()
{
auto t1 = Clock::now();
auto t2 = Clock::now();
std::cout << "Delta t2-t1: "
<< std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1).count()
<< " nanoseconds" << std::endl;
}
Delta t2-t1: 282 nanoseconds
std::chrono::high_resolution_clock
在所有的 std 库实现中都不是单调的。根据 cppreference - 一般情况下,我们应直接使用 std::chrono::steady_clock
或 std::chrono::system_clock
而非 std::chrono::high_resolution_clock
:对于时间间隔的测量,请使用 steady_clock
,对于挂钟时间,请使用 system_clock
。 - Kristianmitkclock()
函数返回程序开始运行以来的时钟计数器值。还有一个相关的常量CLOCKS_PER_SEC
,它告诉你一秒钟内有多少个时钟计数器滴答声。因此,你可以像这样测试任何操作:
clock_t startTime = clock();
doSomeOperation();
clock_t endTime = clock();
clock_t clockTicksTaken = endTime - startTime;
double timeInSeconds = clockTicksTaken / (double) CLOCKS_PER_SEC;
timeInSeconds
总是显示为 0.000000
,我该如何修复它? - noufal也许您对这样的计时器感兴趣:
H:M:S.Msec。
在Linux操作系统中的代码:
#include <iostream>
#include <unistd.h>
using namespace std;
void newline();
int main() {
int msec = 0;
int sec = 0;
int min = 0;
int hr = 0;
//cout << "Press any key to start:";
//char start = _gtech();
for (;;)
{
newline();
if(msec == 1000)
{
++sec;
msec = 0;
}
if(sec == 60)
{
++min;
sec = 0;
}
if(min == 60)
{
++hr;
min = 0;
}
cout << hr << " : " << min << " : " << sec << " . " << msec << endl;
++msec;
usleep(100000);
}
return 0;
}
void newline()
{
cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
}
usleep
不总是在您要求的确切时间后返回。有时它会更长。您应该在开始时检查当前时间,然后检查当前时间并减去每次循环通过的绝对时间,以获取自启动以来的绝对时间。 - Peter Cordes#include <iostream>
#include <ctime>
#include <cstdlib> //_sleep() --- just a function that waits a certain amount of milliseconds
using namespace std;
int main()
{
clock_t cl; //initializing a clock type
cl = clock(); //starting time of clock
_sleep(5167); //insert code here
cl = clock() - cl; //end point of clock
_sleep(1000); //testing to see if it actually stops at the end point
cout << cl/(double)CLOCKS_PER_SEC << endl; //prints the determined ticks per second (seconds passed)
return 0;
}
//outputs "5.17"
(double)clock() / CLOCKS_PER_SEC
,需要包含 ctime。time.clock()
以浮点数返回秒数。System.nanoTime()
以纳秒返回长整型数值。cout << (double)clock() / CLOCKS_PER_SEC;
预期输出: 表示每秒钟的时钟滴答数
的输出
perf stat -d ./a.out
。 - Peter Cordes