Skip to content

Instantly share code, notes, and snippets.

@TylerB24890
Created May 3, 2024 18:28
Show Gist options
  • Save TylerB24890/4c64af8ca3553ae319c33f95212c3eae to your computer and use it in GitHub Desktop.
Save TylerB24890/4c64af8ca3553ae319c33f95212c3eae to your computer and use it in GitHub Desktop.
PHP Process Timer
<?php
/**
* Process Timer.
* Create a system timer for determining the run-time of a specific process.
*
* Usage:
* $timer = new \Tyme\ProcessTimer();
* $timer->start();
* // Long running process
* $timer->stop();
* echo $timer->get_time();
*
* @package Tyme
*/
namespace Tyme;
/**
* ProcessTimer Object
*/
class ProcessTimer {
/**
* Timestamp of start time
*
* @var int
*/
public $time_start = 0;
/**
* Timestamp of end time
*
* @var int
*/
public $time_end = 0;
/**
* Start timer
*
* @return float Start time
*/
public function start() {
global $tyme_timer_start;
$tyme_timer_start = self::current_time();
$this->time_start = $tyme_timer_start;
return $this->time_start;
}
/**
* Stop timer
*/
public function stop() {
global $tyme_timer_end;
$tyme_timer_end = self::current_time();
$this->time_end = $tyme_timer_end;
}
/**
* Get the total runtime.
*
* @param boolean $format Format the runtime?
* @return float
*/
public function get_time( $format = true ) {
$time_total = $this->time_end - $this->time_start;
if ( $format && 0 < $time_total ) {
if ( function_exists( 'number_format_i18n' ) ) {
$time_total = number_format_i18n( $time_total, 3 );
} else {
$time_total = number_format( $time_total, 3 );
}
}
return $time_total;
}
/**
* Get current time in microtime
*
* @return float
*/
public static function current_time() {
return microtime( true );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment