public function tests() { PHPUsableTest::$current_test = $this; describe('Profile', function ($test) { describe('run', function ($test) { it('should record memory usage', function ($test) { $data = Profile::run(function () { }); $test->assertArrayHasKey('memory before', $data); $test->assertArrayHasKey('memory after', $data); $test->assertArrayHasKey('memory peak', $data); }); it('should record elapsed times', function ($test) { $data = Profile::run(function () { }); $test->assertArrayHasKey('elapsed', $data); }); it('should record granular marks', function ($test) { $data = Profile::run(function ($markFunc) { $markFunc(); $markFunc(); $markFunc(); }); $test->assertArrayHasKey('marks', $data); $test->assertEquals(3, count($data['marks'])); }); }); }); }
public static function run($fn, $options = array()) { $memory_before = memory_get_usage(); $time_before = microtime(true); $elapsed = function () use($time_before) { return microtime(true) - $time_before; }; $marks = array(); $markFunc = function ($label = "mark") use(&$marks, $elapsed) { $memory = Profile::humanizeMemory(); $formatted_time_delta = $elapsed(); $marks[] = "{$label}: {$formatted_time_delta} - {$memory}"; }; if (Arrays::get($options, 'debug', false)) { Trace::traceOffset(1)->debug('Staring profile.'); } // The callback provided to the profile closure will trigger // a measurement. $fn($markFunc); $memory_after = memory_get_usage(); $memory_peak = memory_get_peak_usage(true); $data = array('elapsed' => $elapsed(), 'memory_before' => $memory_before, 'memory_after' => $memory_after, 'memory_peak' => $memory_peak, 'marks' => $marks); if (Arrays::get($options, 'debug', false)) { Trace::traceDepth(2)->traceOffset(1)->debug($data); } return $data; }