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
  • 53
  • 6
  • You cannot handle it with `clock`, you need a different function. – n. m. could be an AI Mar 24 '19 at 10:29
  • 1
    What about using [`std::chrono::system_clock::now()`](https://en.cppreference.com/w/cpp/chrono/system_clock/now) ? – πάντα ῥεῖ Mar 24 '19 at 10:37
  • 1
    @πάνταῥεῖ It is probably better to recommend `std::chrono::steady_clock` for timing stuff because system time can shift around as the OS can keep correcting it to keep up with internet time servers and the like. – Galik Mar 24 '19 at 11:24

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.
  • 50,738
  • 9
  • 71
  • 96