Subsecond times - the microtime() function

While a Unix timestamp represents a date and time accurate to the second, many applications require times to be represented to the subsecond. PHP provides the function:


microtime function return current Unix timestamp with microseconds.

mixed microtime ([ bool $get_as_float = false ] )

This fucntion accept one optional parameter get_as_float, if used and set to TRUE, microtime() will return a float instead of a string.

microtime example

string microtime(  )

This returns a string that contains both a Unix timestamp in seconds and a microsecond component. The returned string begins with the microsecond component, followed by the integer timestamp:

// prints the time now in the format "usec sec"
// e.g., 0.34783800 1008553410
echo microtime(  );

Generating random number seed

One common use of the function microtime( ) is to generate the seed for a random-number generator:

// Generate a seed.
$seed = (float)microtime(  ) * 100000000;

Because the microsecond component appears at the start of the string returned from microtime( ), the returned value can be converted to a float with the (float) cast operator. Multiplying the float result by 100,000,000 ensures that you pass a suitably varying integer to the seeding function srand( ). Random-number generation is covered in more detail in next tutorial.