我怎么clock()
打电话C++
?
例如,我想测试线性搜索在数组中找到给定元素所需的时间。
#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';
}
自 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;
}
在 ideone.com 上运行它给了我:
Delta t2-t1: 282 nanoseconds
clock()
返回自程序启动以来的时钟滴答数。有一个相关的常数 ,CLOCKS_PER_SEC
它告诉您在一秒钟内发生了多少时钟滴答。因此,您可以像这样测试任何操作:
clock_t startTime = clock();
doSomeOperation();
clock_t endTime = clock();
clock_t clockTicksTaken = endTime - startTime;
double timeInSeconds = clockTicksTaken / (double) CLOCKS_PER_SEC;
至少在 Windows 上,唯一实际准确的测量机制是 QueryPerformanceCounter (QPC)。std::chrono 是使用它实现的(从 VS2015 开始,如果你使用它的话),但它的准确程度与直接使用 QueryPerformanceCounter 不同。特别是它声称以 1 纳秒的粒度报告是绝对不正确的。所以,如果你测量的东西需要很短的时间(你的情况可能就是这种情况),那么你应该使用 QPC,或者你的操作系统的等价物。我在测量缓存延迟时遇到了这个问题,我在这里记下了一些你可能会觉得有用的笔记; https://github.com/jarlostensen/notesandcomments/blob/master/stdchronovsqcp.md
你可以衡量你的程序运行了多长时间。以下函数有助于测量自程序启动以来的 CPU 时间:
(double)clock() / CLOCKS_PER_SEC
包含ctime的C++ 。time.clock()
以秒为单位返回浮点值。System.nanoTime()
以纳秒为单位返回 long 值。我的参考:加州大学圣地亚哥分校和国立研究大学高等经济学院数据结构和算法专业化的算法工具箱第 1 周课程部分
所以你可以在你的算法之后添加这行代码:
cout << (double)clock() / CLOCKS_PER_SEC;
预期输出:代表数量的输出clock ticks per second
#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"
可能您可能对这样的计时器感兴趣:H:M:S。毫秒。
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";
}