执行时间以C++显示:cin/scanf/getchar_unlocked()

Execution time display in C++: cin/scanf/getchar_unlocked()

本文关键字:getchar unlocked scanf 执行时间 C++ 显示 cin      更新时间:2023-10-16

我正在做一个项目,以证明std::cin在接受输入方面比scanf慢,而反过来又比使用getchar/getchar_unlocked()等通过自写函数获取输入要慢。

我想记录和打印每种情况下的执行时间,但我不知道如何应用时间和时间等头文件。
我将从 stdin 读取大量输入值,并希望显示每种情况下的执行时间。

请用一个简短的例子告诉我如何处理时间。

像这样的东西怎么样

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() <<
    " microsecondsn";

(或多或少逐字摘自此参考资料及其子页面。更具体地说,从std::chrono::time_point引用的第二个示例中,只是更改了使用的时钟。

代码的作用是从高分辨率时钟获取当前时间作为开始时间,执行要成为时间的操作,然后获取结束时间。然后,它以微秒为单位显示差异。

#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);
}

然后根据需要调用这两个方法。

#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.