0

I need to measure execution time of the program using clock() function. The whole algorithm consists of the input of one character.

I found how to measure time with clock() here: How to use clock() in C++.

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

Program always output 0. This is due to the fact that when performing cin, there are no processor counts? How can I handle this problem?

CyberFlex
  • 43
  • 5

1 Answers1

1

Use the std::chrono facilities for this:

#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";
Nikos C.
  • 49,123
  • 9
  • 66
  • 95