Completed
Pull Request — master (#4)
by mw
10:59
created

CallFuncMemorySniffer::memoryTick()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 0
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
	public static function memoryTick() {
32
		self::$memory = memory_get_usage() - self::$memory;
33
		self::$max    = self::$memory > self::$max ? self::$memory : self::$max;
34
		self::$memory = memory_get_usage();
35
	}
36
37
	/**
38
	 * @since 2.0
39
	 *
40
	 * @param callable $func
41
	 * @param array|null $args
42
	 *
43
	 * @return mixed
44
	 */
45
	public function call( callable $func, $args = null ) {
46
47
		declare( ticks=1 );
48
49
		self::$memory = memory_get_usage();
50
		self::$max    = 0;
51
52
		register_tick_function(
53
			'call_user_func_array',
54
			array( '\Onoi\CallbackContainer\CallFuncMemorySniffer', 'memoryTick' ),
55
			array()
56
		);
57
58
		$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
		$result = is_array( $args ) ? call_user_func_array( $func, $args ): call_user_func( $func );
60
		$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
		unregister_tick_function( 'call_user_func_array' );
63
64
		return $result;
65
	}
66
67
	/**
68
	 * @since 2.0
69
	 *
70
	 * @return integer
71
	 */
72
	public function getMemoryUsed() {
73
		return self::$max;
74
	}
75
76
	/**
77
	 * @since 2.0
78
	 *
79
	 * @return float
80
	 */
81
	public function getTimeUsed() {
82
		return $this->time;
83
	}
84
85
}
86