Timestamp PHP function

This code snippet serves as a benchmarking tool to measure the execution time of a specific code block by iterating through a defined number of times. It captures the start and end times using microtime(true) before and after the code block, respectively, and calculates the total time taken by subtracting the start time from the end time. The total time is then formatted for readability and displayed, providing developers with valuable insights into the performance of their code, facilitating optimization efforts where necessary.

<?php
// Number of iterations to perform
$iterations = 1000000;

// Start time before the code block
$start_time = microtime( true );

// Code block to benchmark
for ($i = 0; $i < $iterations; $i++) {
    // Some time-consuming operation
}

// End time after the code block
$end_time = microtime( true );

// Calculate the total time taken
$total_time = $end_time - $start_time;

// Format the total time to display as seconds with 6 decimal places
$total_time_formatted = number_format($total_time, 6);

// Print the benchmark results
echo '<p>Start Time: ' . $start_time . '</p>';
echo '<p>End Time: ' . $end_time . '</p>';
echo '<p>Total Time: ' . $total_time_formatted . ' seconds</p>';
?>
Leave a Reply 0

Your email address will not be published. Required fields are marked *