PHP's microtime() function & floating point number display precision

PHP's microtime() function & floating point number display precision

Ahem, I have always been entangled in the naming of this function. Obviously, it returns seconds. I have to put a micro in the name. It always makes me think that the return to Shanghai is microseconds (microseconds).

In fact, the function of this function is to return the time with microseconds . The statement in PHP is as follows:

mixed microtime ([ bool $get_as_float = FALSE ] )

Regarding the return value, this is described in the document

By default, microtime() returns a string in the form "msec sec", where sec is the number of seconds since the Unix epoch (0:00:00 January 1,1970 GMT), and msec measures microseconds that have elapsed since sec and is also 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.

That is to say, if the parameter TRUE is not added , the form returned is "msec sec", where msec is also expressed in seconds, that is, seconds in decimal form.

If you add the parameter TRUE , you can understand it better, that is, seconds with decimals.

Let's write a simple code to have a look

<?
$mt=microtime();
$mt_f=microtime(true);
var_dump($mt);
var_dump($mt_f);
?>

The output is as follows:

But why is there only two digits after the decimal point in seconds expressed in floating-point numbers? How can this be accurate to microseconds? In fact, this is only caused by the display accuracy setting of floating-point numbers, and does not affect the accuracy of operations (such as finding the time difference).

If you want to make it display with higher precision, you can try the following code:

<?
echo ini_get("precision"), "\n";
ini_set("precision",16);
$mt=microtime();
$mt_f=microtime(true);

var_dump($mt);
var_dump($mt_f);
?>

The output is as follows:

It can be seen that the default floating-point number display precision was 12 digits before, and after we set it to 16 digits, it will display to 6 digits after the decimal point.

Okay, just talk about these. Actually, I wanted to be more talkative, but the browser crashed. I re-typed these. This mood is so sour and refreshing.

Reference: https://cloud.tencent.com/developer/article/1580039 PHP's microtime() function & floating point number display accuracy-Cloud + Community-Tencent Cloud