简体   繁体   中英

Convert system clock (microsecond) stored in int64_t to float(s)?

Currently I have a function, f(), which returns the current system clock in microseconds. I need to convert it to seconds, preserving several digits after the decimal point. I want to store the result in a float(is it long enough?).

But what f() returns is a int64_t variable; I tried many methods, like:

(double)(f() / 1000000) + (double)((f() % 1000000) / (double)1000000);

and:

f() / 100000.f

But what I got in fact looks like "1318395904.000000".

UPDATE:

What I want to do is to calculate FPS of my program. It seems converting it into second first is a bad idea. I rewrote my program like this, and both method work well:

(PS, av_gettime() is the function f() I mentioned.)

std::cout << "Yoooooo FPS: " << (float)5000000 / (float)(av_gettime() - prevFrameShowTime)
          << std::endl;
std::cout << "Current FPS: " << (double)5000000 / (double)(av_gettime() - prevFrameShowTime)
          << std::endl;

And here is the output:

Yoooooo FPS: 60.623
Current FPS: 60.6097

Your float has (assuming IEEE-754) 23 bits for the mantissa, how do you expect to store a 64-bit value in there without losing precision?

(The value you showed needs 31 bits just to store whole seconds, your precision is only to the nearest 128 seconds)

A typical 32-bit float will give you about seven significant digits of precision. All your significant digits are being used by the whole part. You'll need to use a double.

First you convert it to double , then divide:

double result = (double) f() / 1000000.0;

Btw, yes, I would store the result in double here, not float .

你将失去一些精确度,但这应该工作:

(double) f() / 1000000

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM