Why does clock () return 1.84467e + 13?

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

Why is this happening?

Here is a minimal 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; } 
+5
source share
2 answers

Your clock_t seems to be an unsigned 64-bit type.

You take a tick - tock where the tock was measured after the tick , so if there is any difference between them at all, it will try to create a negative number, but since it is an unsigned type that wraps around to become something close to the largest the number that can be represented in this type.

Obviously, you really want to use tock-tick .

+12
source

let tic = 2ms and tac - 4 ms; so when you do tic-tac (2-4), which will generate a negative number, obviously, even if it gives a positive number, it will not be in real time. as well as the number that it generates (which does not appear on my computer) - a large number, so try using the manipulator;

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

he can work.

-2
source

Source: https://habr.com/ru/post/1238473/


All Articles