Last active
July 12, 2020 09:12
-
-
Save RadGH/d8decea445d496270fe6894ca1252254 to your computer and use it in GitHub Desktop.
Get time difference from start to end in seconds, for measuring speed of operations in php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// How to use: | |
// 1. Copy the class at the end of the file into your code. | |
// 2. Follow the examples below for usage. | |
// ----------------------- | |
// Example #1: Basic usage | |
// Start | |
$timing = new Code_Timer(); | |
// Some operation that takes awhile... | |
sleep( 2 ); | |
// Get time taken in seconds | |
$time_taken = $timing_total->get_time_diff(); // 2.0301481303 | |
// Format the result with 2 decimal places | |
echo 'Process took about ' . number_format( $time_taken, 2 ) . ' seconds.'; | |
// ----------------------- | |
// Example 2: As a reusable timer | |
$pdf_timer = new Code_Timer(); | |
$times = array(); | |
for( $i = 0; $i < 10; $i++ ) { | |
$pdf_timer->start(); | |
create_a_pdf(); // example user-made function | |
$times[] = $pdf_timer->get_time_diff(); | |
} | |
// Display average of each individual timer | |
echo 'PDFs take an average of '. array_sum($times) / count($times) . ' seconds to generate.'; | |
/** | |
* Class Code_Timer | |
* Get the time difference between two pieces of the code, used to measure how long your code takes to run. | |
*/ | |
if ( !class_exists('Code_Timer') ) { | |
class Code_Timer { | |
private $start_time; | |
// Create the timer and start timing immediately | |
public function __construct() { | |
$this->start(); | |
} | |
// (Re)start the timer | |
public function start() { | |
$this->start_time = microtime(true); | |
} | |
// Get time diff in seconds from when it was last started | |
public function get_time_diff() { | |
return (microtime(true) - $this->start_time); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment