Snippets

Nicola Moretto PHP microtime() parser rounding issue

Created by Nicola Moretto last modified
<?php
// The script shows a potential issue with rounding PHP microtime() timestamp to extract milliseconds
while(true) {
    $timestamp = explode(' ', microtime());
    $now = new \DateTime();
    $now->setTimestamp($timestamp[1]);
    if (preg_match('/^0\.999[56789]/', $timestamp[0]) === 1) {
        echo "microtime(): $timestamp[0]\n";
        echo "expected: " . substr($timestamp[0] * 1000, 0, 3) . "\n";
        echo "effective: " . round($timestamp[0] * 1000) . "\n";
        break;
    }
}

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.