Implicit casting from float to int | Sololearn: Learn to code for FREE!


Implicit casting from float to int

In this code( ) i was trying to calculate the elapsedTime per seconds in each loop. the normal value should range from 1.0e-2 to 1.7e-2, which should be 55 to 60 frame per seconds. But instead, the output is an integer of zero. I think this is because the expression std::abs(t1 - t0) / CLOCKS_PER_SECOND Was implicitly casted to an integer. I tried using std::fabs() and explicit cast to float on the CLOCKS_PER_SECOND macro and it still won't work as expected. How do i get the precise value for fElapsedtime so it output values within range instead of just 0. Look at the python's output


5/6/2021 5:28:18 PM


8 Answers

New Answer


Mirielle check the code, it's working! time() -  measures the real time and like you mentioned execution speed of 0.0000000000000n makes no difference in real time and hence we have two same values for t0 and t1. clock() - measures the processing time taken by the current process. Also there is "clocks" in CLOCKS_PER_SEC and hence more precise. Also, you will need to multiple the elapse time by 1.0 so to make it a decimal(for c/c++)


t0 and t1 they both have the same value and hence 0. (edit) check this...


std::time returns a struct time_t. time_t almost always represents the time as an integer to represent the number of seconds. ( almost as in this is not actually defined but most implementations do this ) Calling std::time so close together without anything in between almost always returns the same value. so t1 - t0 == 0 and 0 / 1'000'000 = even more 0. I recommend using the std::chrono library instead. Using that library I rewrote the code to:


Also, I would like to add that instead of using std::time, you can use std::clock. std::clock is more precise because it measures the processor time spend on the application instead of the amount of seconds. (rkk beat me to it)


This version gives an exact output range within 0.01 - 0.011(OK)


rkk yeah right, how is that even possible. Shouldn't there be atleast a very small difference between the two calls. Maybe 0.000000000000000n


Check value of t1-t0, isn't it 0?


I've seen the most people prefer chrono to time. I havent reached the chrono chapter yet but i just think time should do what i wanted