1 : <?php
2 :
3 : /**
4 : * XSLT Benchmarking
5 : * @link https://github.com/masicek/XSLT-Benchmarking
6 : * @author Viktor Mašíček <viktor@masicek.net>
7 : * @license "New" BSD License
8 : */
9 :
10 : namespace XSLTBenchmarking\TestsRunner;
11 :
12 : require_once __DIR__ . '/AMemoryUsageDriver.php';
13 : require_once ROOT . '/Exceptions.php';
14 : require_once LIBS . '/PhpPath/PhpPath.min.php';
15 :
16 : use PhpPath\P;
17 :
18 : /**
19 : * Linux driver for geting maximum memory usage of command excuteb by 'exec'
20 : *
21 : * @author Viktor Mašíček <viktor@masicek.net>
22 : */
23 : class LinuxMemoryUsageDriver extends AMemoryUsageDriver
24 : {
25 :
26 :
27 : /**
28 : * Path of log file for reporting measured PeakWorkingSetSize from '/usr/bin/time'
29 : *
30 : * @var string
31 : */
32 : private $logPath;
33 :
34 : /**
35 : * Path of script included running command for running in '/usr/bin/time'
36 : *
37 : * @var string
38 : */
39 : private $scriptPath;
40 :
41 :
42 : /**
43 : * Construct path of main and end log files
44 : *
45 : * @param type $tmpDir Path of temporary directory
46 : */
47 : public function __construct($tmpDir)
48 : {
49 0 : parent::__construct($tmpDir);
50 :
51 0 : $this->logPath = P::m($this->tmpDir, 'linuxMemoryUsage.log');
52 0 : $this->scriptPath = P::m($this->tmpDir, 'linuxMemoryUsage.sh');
53 0 : }
54 :
55 :
56 : /**
57 : * Save command into scrit and return command for running set command and
58 : * checking its memory usage.
59 : *
60 : * @param string $command Checked command
61 : *
62 : * @throws \XSLTBenchmarking\InvalidArgumentException Log/Script file exist
63 : * @return string
64 : */
65 : public function run($command)
66 : {
67 0 : if (is_file($this->logPath))
68 0 : {
69 0 : throw new \XSLTBenchmarking\InvalidArgumentException('Linux memory usage log file exist.');
70 : }
71 0 : if (is_file($this->scriptPath))
72 0 : {
73 0 : throw new \XSLTBenchmarking\InvalidArgumentException('Linux memory usage script file exist.');
74 : }
75 :
76 0 : file_put_contents($this->scriptPath, $command);
77 0 : chmod($this->scriptPath, 0777);
78 :
79 : $command =
80 0 : '/usr/bin/time -v ' . $this->scriptPath . ' 2>&1 | ' .
81 0 : 'grep \'Maximum resident set size (kbytes):\' | ' .
82 0 : 'sed \'s/^.*: //\' > ' . $this->logPath;
83 :
84 0 : return $command;
85 : }
86 :
87 :
88 : /**
89 : * Return maximum memory usage (in bytes) last checked command by self::run().
90 : *
91 : * @return integer
92 : */
93 : public function get()
94 : {
95 0 : $maxMemory = file_get_contents($this->logPath);
96 0 : $maxMemory = trim($maxMemory);
97 :
98 0 : unlink($this->logPath);
99 0 : unlink($this->scriptPath);
100 :
101 : // units corrections (Kilobytes -> Bytes)
102 0 : $maxMemory = $maxMemory * 1000;
103 :
104 0 : return $maxMemory;
105 : }
106 :
107 :
108 : }
|