当我使用 cin 时,我如何使用 clock() 测量时间



我需要使用 clock(( 函数测量程序的执行时间。整个算法由一个字符的输入组成。

我在这里找到了如何使用 clock(( 测量时间:如何在 C++中使用 clock((。

#include <cstdio>
#include <ctime>
int main() {
    std::clock_t start;
    double duration;
    start = std::clock();
    std::cout << "Press a key followed by ENTER: ";
    char c;
    cin >> c;
    duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
    std::cout<<"printf: "<< duration <<'n';
}

程序始终输出 0。这是因为在执行 cin 时,没有处理器计数?我该如何处理这个问题?

为此使用std::chrono工具:

#include <chrono>
// ...
auto start = std::chrono::steady_clock::now();
std::cout << "Press a key followed by ENTER: ";
char c;
std::cin >> c;
std::chrono::nanoseconds elapsed_ns = std::chrono::steady_clock::now() - start;
std::cout << "This took " << elapsed_ns.count() << " nanoseconds.n";

最新更新