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
.
You are going to lose some precision, but this should work:
(double) f() / 1000000
精彩评论