我正在开展一个项目,以显示std::cin
与scanf
相比输入速度较慢,getchar/getchar_unlocked()
反过来比使用{{1}}通过自写函数输入更慢等等。
我想在每种情况下记录和打印执行时间,但我不知道如何应用时间和计时等头文件。
我将从stdin读取大量输入值,并希望在每种情况下显示执行时间。
请用一个简短的例子告诉我如何处理时间。
答案 0 :(得分:3)
像
这样的东西auto start = std::chrono::high_resolution_clock::now();
some_long_running_operation();
auto end = std::chrono::high_resolution_clock::now();
std::cout << "Operation took " <<
std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() <<
" microseconds\n";
(或多或少采用逐字from this reference及其子页面。更具体地来自std::chrono::time_point
引用的第二个示例,只更改了使用的时钟。)
代码的作用是从高分辨率时钟获取当前时间作为开始时间,执行时间操作,然后获取结束时间。然后它以微秒显示差异。
答案 1 :(得分:2)
#include <time.h>
clock_t t;
void startTimer() {
t = clock();
}
void stopTimer() {
t = clock() - t;
printf("It took me %d clicks (%f seconds).\n", t, ((float)t) / CLOCKS_PER_SEC);
}
然后根据需要调用这两种方法。
OR
#include <sys/time.h>
#include <iostream>
using namespace std;
struct timeval t1, t2;
struct timezone tz;
void startTimer()
{
gettimeofday(&t1, &tz);
}
void stopTimer()
{
gettimeofday(&t2, &tz);
cout<<"It took "<< t2.tv_sec - t1.tv_sec <<" seconds and "<< t2.tv_usec - t1.tv_usec<<" microseconds"<<endl;;
}
// call "startTimer()" to start timer
// call "stopTimer()" to stop timer and print total time in microseconds.