-1

I use this to mesure elapsed time :

const clock_t begin_time = clock();
// code here

cout << float( clock () - begin_time ) /  CLOCKS_PER_SEC;   //return 1.234

float var = ( clock () - begin_time ) /  CLOCKS_PER_SEC;
cout << var;                                                //return 1

Please explain me i don't understand what is going on.

EDIT : why the printed var doesn't have the ".234" ?

Maarethyu
  • 83
  • 1
  • 9
  • Please explain, we don't understand what you're asking. What value do you get and what value are you expecting? why do you think the value is wrong? – Captain Obvlious Apr 27 '15 at 23:09
  • 1
    `clock_t` is an integral type, so the second expression performs a integer division. First one is a floating point division (as per the cast) – SleuthEye Apr 27 '15 at 23:09

1 Answers1

0

The first expression:

float( clock() - begin_time) / CLOCKS_PER_SEC;

converts the subsexpression clock() - begin_time to a floating-point value, which then means that the whole expression corresponds to a floating-point division (the result of which is 1.234f in your example).

In the second expression:

( clock() - begin_time) / CLOCKS_PER_SEC;

all arguments are of integral type, thus an integer division is performed. The result of which is an integer value (in your example 1). Only later is the result converted to float (1.0f) to be assigned to the floating-point variable var.

If you want to store the result in float variable var you can use:

float var = float( clock() - begin_time ) / CLOCKS_PER_SEC;
cout << var;
SleuthEye
  • 14,379
  • 2
  • 32
  • 61