0

I am trying to understand how the various data types are controlling the way output of microtime() function is displayed?

here are the 3 scenarios:

1 . This will display the output of the microtime function in floating format since I have set the boolean value to true.

I want to know, how many decimal places by default will the float function display (in this case it is 4)?

How is that related to the architecture of the CPU?

lab$ php -r 'echo microtime(true),"\n";'
1361544317.2586

2 . Here, the output of microtime() function is being type cast to double format.

So, does it mean, it will show only upto 6 decimal places of microseconds? How is it different from float and its maximum size/precision?

lab$ php -r 'echo (double)microtime(),"\n";'
0.751238

3 . This is the default usage of microtime() function, where it prints both the microseconds and the unix epoch timestamp:

lab$ php -r 'echo microtime(),"\n";' output: 0.27127200 1361544378

I wanted to understand this, because in many places I have seen that microtime() is being used to generate the seed for mt_rand() PRNG in this way:

mt_srand((double)microtime() * 1000000)

What is the use of typecasting here and multiplying with 10^6? And what is the maximum possible value of the parameter to mt_srand()?

thanks.

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
Neon Flash
  • 3,113
  • 12
  • 58
  • 96

1 Answers1

1

There is one problem with floating point numbers: You can either have large numbers or a high floating point precision. This problem doesn't fit to the problem of a large number of seconds (seconds since 1970/1/1) and a high precison - microseconds.


PHP tries to solve that issue by returning the floating point part of the timestamp and the number of full seconds since the epoch as two separated values in a string.

For situations where the precision is less important PHP also supports returning the timestamp as a float value, rounded to the nearest microsecond. On my system the accuracy is a 10.000th's second as in your example. I don't know if this is granted.

Quote from the PHP manual:

By default, microtime() returns a string in the form "msec sec", where sec is the current time measured in the number of seconds since the Unix epoch (0:00:00 January 1, 1970 GMT), and msec is the number of microseconds that have elapsed since sec expressed in seconds.

If get_as_float is set to TRUE, then microtime() returns a float, which represents the current time in seconds since the Unix epoch accurate to the nearest microsecond.

This means, if you need the most accurate precision you should use microtime() without the param get_as_float and then create the final timestamp using string and / or bc_math operations.

Community
  • 1
  • 1
hek2mgl
  • 152,036
  • 28
  • 249
  • 266