Understanding PHP microtime() Function and Measuring Execution Time

This article explains how PHP's microtime() function returns the current Unix timestamp with microseconds, describes its optional parameter behavior, and provides a reusable example that measures script execution time using a custom microtime_float() helper.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Understanding PHP microtime() Function and Measuring Execution Time

The microtime() function returns the current Unix timestamp together with microseconds. When called without arguments it returns a string in the format "msec sec", where sec is the number of seconds since the Unix epoch and msec is the microsecond part.

If the optional boolean parameter $get_as_float is set to true, the function returns a float representing the full timestamp (seconds plus fractional microseconds).

Below is a practical example that defines a microtime_float() helper to obtain a float timestamp, measures the time taken by a short operation, and outputs the elapsed time.

<?php
/**
 * Simple function to replicate PHP 5 behaviour
 */
function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

$time_start = microtime_float();
// Sleep for a while
usleep(100);
$time_end = microtime_float();
$time = $time_end - $time_start;

echo "Did nothing in $time seconds
";
?>

The script records the start time, pauses execution for 100 microseconds with usleep(), records the end time, calculates the difference, and prints the elapsed time, demonstrating how to use microtime() for performance measurement.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

performancePHPmicrotimetiming
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.