Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is clock() returning 1.84467e+13?

Tags:

c++

timing

clock

I am trying to time a code I've got in C++. I have an inner and an outer loop that I want to time separately, but at the same time. For some reason when I do this one of the instances returns 1.84467e+13 and always this exact number.

Why is this happening?

Here is a minimum working example that replicates the effect on my machine:

#include <iostream>
#include <stdlib.h>
#include <time.h>

using namespace std;

int main()
{
    long int i, j;
    clock_t start, finish, tick, tock;
    double a = 0.0;
    double adding_time, runtime;

    start = clock();
    for(i=0; i<10; i++)
    {
        a=0.0;
        tick =clock();
        for(j=0; j<10000000; j++)
        {
            a+=1;
        }
        tock= clock();
        adding_time = (double)(tick - tock)/CLOCKS_PER_SEC;
        cout << "Computation time:" << adding_time << endl;

    }
    finish = clock();
    runtime = (double)(finish - start)/CLOCKS_PER_SEC;
    cout << "Total computation time:" << runtime << endl;
}
like image 593
Phill Avatar asked Dec 17 '15 05:12

Phill


1 Answers

Your clock_t is apparently an unsigned 64-bit type.

You're taking tick - tock, where tock was measured after tick, so if there's any difference between the two at all, it's going to try to produce a negative number--but since it's an unsigned type, that's wrapping around to become something close to the largest number that can be represented in that type.

Obviously, you really want to use tock-tick instead.

like image 121
Jerry Coffin Avatar answered Dec 03 '22 13:12

Jerry Coffin