Bamboo
Bamboo

Reputation: 973

Why is clock() returning 1.84467e+13?

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

Upvotes: 5

Views: 513

Answers (2)

Yveslym
Yveslym

Reputation: 11

let say tic = 2ms and tac is 4ms; so when you do tic-tac(2-4) that will generate a negative number obviously.. even if it given a positive number it wont be the real time. and also, the number it generate (which doesnt appear on my computer) is a big number, so, try to use the manipulator;

#include"iomanip" 
    cout << fixed << showpoint;
cout << setprecision(2);

it might work..

Upvotes: -2

Jerry Coffin
Jerry Coffin

Reputation: 490623

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.

Upvotes: 12

Related Questions