the clock function

I read that the clock function returns the elapsed processor time (as measured in clock ticks) since the beginning of the program execution. But then another source says "clock() returns 0 the first time it is called (and thereafter it returns the time since it was first called)". So which is it? Does it begin when program starts or when it is called?
The C standard says:
The clock function returns the implementation’s best approximation to the processor time used by the program since the beginning of an implementation-defined era related only to the program invocation.

The way I understand this is that it starts counting when the program starts but that it doesn't necessarily starts counting from zero.
Last edited on
Nothing more than this is guaranteed:
The difference between the two values returned by two different calls to std::clock() gives an estimate of the processor time used by the process between the two calls.

1
2
3
4
5
6
7
8
const auto start = std::clock() ;
       
    // execute some code to be timed

const auto end = std::clock() ;

std::cout << "that code took approximately " 
          << double(end-start) / CLOCKS_PER_SEC << " processor seconds.\n" ;

http://coliru.stacked-crooked.com/a/fe7151800c29d111
...and even then there is variability. Is it total time elapsed since program start? Or total time consumed by the program's process alone? (The answer depends on the compiler.)

Since you are using C++, you might as well use one of the clock/timers in <chrono>.
http://www.cplusplus.com/reference/chrono/

Hope this helps.
clocks in <chrono> and std::time(): wall clock time.

std::clock(): approximate processor time.

The two are used for different purposes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <ctime>
#include <iostream>
#include <chrono>
#include <thread>

volatile long long v = 0 ;

int main()
{
    constexpr int N = 1024*1024*256 ;
    
    using namespace std::chrono ;
    const auto timepoint_start = steady_clock::now() ;         
    const auto clock_start = std::clock() ;
    
    std::this_thread::sleep_for( seconds(5) ) ;
    for( int i=0 ; i < N ; ++i ) v += 1 ;

    const auto clock_end = std::clock() ;
    const auto timepoint_end = steady_clock::now() ;         

    std::cout << "elapsed processor time: " << double(clock_end-clock_start) / CLOCKS_PER_SEC * 1000.0 << " milliseconds.\n" ;
    std::cout << "elapsed wall clock time: " << duration_cast<milliseconds>(timepoint_end-timepoint_start).count() << " milliseconds.\n" ;
}

http://coliru.stacked-crooked.com/a/5eb18a22b882a31b
Topic archived. No new replies allowed.