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

+12

Implicit casting from float to int

In this code( https://code.sololearn.com/cg5528jWyFH3/?ref=app ) 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

cpp

5/6/2021 5:28:18 PM

Mirielle[ Left SL ]

8 Answers

New Answer

+7

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++) https://code.sololearn.com/cr3b8cG6wn2E/?ref=app

+6

t0 and t1 they both have the same value and hence 0. (edit) check this... https://stackoverflow.com/questions/2808398/easily-measure-elapsed-time

+5

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: https://code.sololearn.com/c5a2a19a24a1

+5

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. https://en.cppreference.com/w/cpp/chrono/c/clock (rkk beat me to it)

+3

This version gives an exact output range within 0.01 - 0.011(OK) https://code.sololearn.com/ccx9OSlKtL2D/?ref=app

+2

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

+1

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

+1

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