Skip to content

Instantly share code, notes, and snippets.

@xphere
Last active December 20, 2015 12:18
Show Gist options
  • Save xphere/6129605 to your computer and use it in GitHub Desktop.
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
<?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