3

I want to use a timer function in my program. Following the example at How to use clock() in C++, my code is:

int main()
{
    std::clock_t start = std::clock();

    while (true)
    {
        double time = (std::clock() - start) / (double)CLOCKS_PER_SEC;
        std::cout << time << std::endl;
    }

    return 0;
}

On running this, it begins to print out numbers. However, it takes about 15 seconds for that number to reach 1. Why does it not take 1 second for the printed number to reach 1?

Community
  • 1
  • 1
Karnivaurus
  • 22,823
  • 57
  • 147
  • 247
  • 2
    You should look at [``](http://en.cppreference.com/w/cpp/chrono) which has the notion of a [`duration`](http://en.cppreference.com/w/cpp/chrono/duration) to do this type of thing – Cory Kramer Feb 16 '16 at 18:12
  • Possible duplicate of [CLOCKS\_PER\_SEC not actually clocks per sec](http://stackoverflow.com/questions/10455905/clocks-per-sec-not-actually-clocks-per-sec) – pyj Feb 16 '16 at 18:20
  • Depends on the OS. But clearly you are generating output much faster than the "terminal" can scroll it. That hits the wall pretty quickly, you'll however have to sit through it trying to catch up. – Hans Passant Feb 16 '16 at 18:27

3 Answers3

2

std::clock returns cpu time, not wall time. That means the number of cpu-seconds used, not the time elapsed. If your program uses only 20% of the CPU, then the cpu-seconds will only increase at 20% of the speed of wall seconds.

AaronI
  • 842
  • 6
  • 12
2

Actually it is a combination of what has been posted. Basically as your program is running in a tight loop, CPU time should increase just as fast as wall clock time.

But since your program is writing to stdout and the terminal has a limited buffer space, your program will block whenever that buffer is full until the terminal had enough time to print more of the generated output.

This of course is much more expensive CPU wise than generating the strings from the clock values, therefore most of the CPU time will be spent in the terminal and graphics driver. It seems like your system takes about 14 times the CPU power to output that timestamps than generating the strings to write.

Bluehorn
  • 2,956
  • 2
  • 22
  • 29
1

std::clock

Returns the approximate processor time used by the process since the beginning of an implementation-defined era related to the program's execution. To convert result value to seconds divide it by CLOCKS_PER_SEC.

So it will not return a second until the program uses an actual second of the cpu time.

If you want to deal with actual time I suggest you use the clocks provided by <chrono> like std::steady_clock or std::high_resolution_clock

NathanOliver
  • 171,901
  • 28
  • 288
  • 402