Skip to content

Instantly share code, notes, and snippets.

@trafficinc
Created December 18, 2020 00:53
Show Gist options
  • Save trafficinc/9b49d93dc8366649b322768187a21246 to your computer and use it in GitHub Desktop.
Save trafficinc/9b49d93dc8366649b322768187a21246 to your computer and use it in GitHub Desktop.
Simple PHP Profiling Performance
<?php
/* ----- Profiling.php ----- */
class Profiling {
public $messages = [];
protected $profile;
protected $current_time;
public function __construct($profile) {
$this->profile = $profile;
$this->current_time = microtime(true);
}
public function prof_flag($str) {
if (!$this->profile) {
return;
}
$this->messages[$str] = ['event' => $str,'time' => round(microtime(true) - $this->current_time, 2)];
}
public function prof_print() {
if (!$this->profile) {
return;
}
$out = [];
foreach($this->messages as $mess) {
$time = (float) $mess['time'];
$out[] = "Event: {$mess['event']} , Time: $time";
}
return "\n". implode("\n", $out) ."\n";
}
}
/* ----- TO USE , sample.php ----- */
require_once "Profiling.php";
$profile = new Profiling(true);
$profile->prof_flag("Start");
/* SOME CODE TO PROFILE */
$profile->prof_flag("Got Request Data");
/* SOME MORE CODE TO PROFILE */
$profile->prof_flag("Complete.");
// Print or Log results
$profile->prof_print();
/*----- OUTPUT: -----
Event: Start , Time: 0
Event: Got Request Data , Time: 0.02
Event: Complete. , Time: 0.05
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment