Completed
Pull Request — master (#4)
by mw
11:15 queued 09:43
created

CallFuncMemorySniffer::getMemoryUsed()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
namespace Onoi\CallbackContainer;
4
5
/**
6
 * @see http://stackoverflow.com/questions/19973037/benchmark-memory-usage-in-php
7
 *
8
 * @license GNU GPL v2+
9
 * @since 2.0
10
 */
11
class CallFuncMemorySniffer {
12
13
	/**
14
	 * @var integer
15
	 */
16
	private static $max;
17
18
	/**
19
	 * @var integer
20
	 */
21
	private static $memory;
22
23
	/**
24
	 * @var integer
25
	 */
26
	private $time;
27
28
	/**
29
	 * @since 2.0
30
	 */
31 2
	public static function memoryTick() {
32 2
		self::$memory = memory_get_usage() - self::$memory;
33 2
		self::$max    = self::$memory > self::$max ? self::$memory : self::$max;
34 2
		self::$memory = memory_get_usage();
35 2
	}
36
37
	/**
38
	 * @since 2.0
39
	 *
40
	 * @param callable $func
41
	 * @param array|null $args
42
	 *
43
	 * @return mixed
44
	 */
45 2
	public function call( callable $func, $args = null ) {
46
47 2
		declare( ticks=1 );
48
49 2
		self::$memory = memory_get_usage();
50 2
		self::$max    = 0;
51
52 2
		register_tick_function(
53 2
			'call_user_func_array',
54 2
			array( '\Onoi\CallbackContainer\CallFuncMemorySniffer', 'memoryTick' ),
55 2
			array()
56 2
		);
57
58 2
		$this->time = microtime( true );
0 ignored issues
show
Documentation Bug introduced by
The property $time was declared of type integer, but microtime(true) is of type double. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
59 2
		$result = is_array( $args ) ? call_user_func_array( $func, $args ): call_user_func( $func );
60 2
		$this->time = microtime( true ) - $this->time;
0 ignored issues
show
Documentation Bug introduced by
The property $time was declared of type integer, but microtime(true) - $this->time is of type double. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
61
62 2
		unregister_tick_function( 'call_user_func_array' );
63
64 2
		return $result;
65
	}
66
67
	/**
68
	 * @since 2.0
69
	 *
70
	 * @return integer
71
	 */
72 2
	public function getMemoryUsed() {
73 2
		return self::$max;
74
	}
75
76
	/**
77
	 * @since 2.0
78
	 *
79
	 * @return float
80
	 */
81 2
	public function getTimeUsed() {
82 2
		return $this->time;
83
	}
84
85
}
86