Last active
December 20, 2015 12:18
-
-
Save xphere/6129605 to your computer and use it in GitHub Desktop.
Returns integer difference between calls to a callback.
Mainly for usage with memory_get_usage and memory_get_peak_usage
This file contains hidden or 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 | |
/** | |
* Returns integer difference between calls to a callback | |
* Mainly for usage with memory_get_usage and memory_get_peak_usage | |
* | |
* Usage: | |
* $memDiff = new Diff(function() { return memory_get_usage(true); }); | |
* do_somethin_memory_intensive(); | |
* echo $memDiff; | |
*/ | |
class Diff | |
{ | |
protected $previous; | |
protected $current; | |
protected $autoUpdate; | |
public function __construct(\Closure $callback, $callNow = true, $autoUpdate = true) | |
{ | |
$this->autoUpdate = (bool) $autoUpdate; | |
$this->callback = $callback; | |
if ($callNow) { | |
$this->update(); | |
} | |
} | |
public function getCurrent() | |
{ | |
return $this->current; | |
} | |
public function update() | |
{ | |
$this->previous = $this->current; | |
return $this->current = call_user_func($this->callback); | |
} | |
public function getDiff() | |
{ | |
return $this->current - $this->previous; | |
} | |
public function __toString() | |
{ | |
if ($this->autoUpdate) { | |
$this->update(); | |
} | |
$diff = $this->getDiff(); | |
return ($diff > 0 ? '+' : '') . $diff; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment