Cpu_get_usage in php?

I created a test class that allows the user to embed, for example,

$timer->checkpoint('1'); 

to check the code for time, memory consumption, etc. and at the end of the code, if he / she wants to test it, he / she should insert

 $result=$timer->result(); 

this gives some data for the result of the public function (), for example, for example. memory usage (using memory_get_peak_usage) and time consumption (microtime ()).

All of this works great for me.

But how can I use a combination of existing built-in php functions to get a value that can be considered processor consumption ?

It was pretty easy to calculate how much time was spent on a specific piece of code using the built-in functions, but I had trouble thinking about how to get CPU consumption for a specific piece of code.

+6
source share
2 answers

I hate answering my own question, but I researched a lot, and here I go ... Basically, I did it ...

  $dat=getrusage(); foreach ($dat as $key => $val) { $usertime= $dat['ru_utime.tv_usec']; $systemtime= $dat['ru_stime.tv_usec']; $finalresultcpu= ($systemtime + $usertime); } $this->_cpuTrackers[$name]=$finalresultcpu; return $this; } 

As you can see, I used the built-in getrusage function. Which produces an array with a number of information, most of which was completely useless to me, with the exception of ru_utime.tv_usec (user time) and ru_stime.tv_usec (system time). To find out how much CPU power the script consumed, we need to look at the values ​​of "user time" and "system time", and, as you can see in the code, add it to get the time, which is actually processor usage.

+5
source
 function cpu_usage(){ static $R=0; $r=$R; $R=getrusage(); $R= $R['ru_utime.tv_sec']*1000000+$R['ru_utime.tv_usec']+ $R['ru_stime.tv_sec']*1000000+$R['ru_stime.tv_usec']; return $R-$r; } 

Using:

 cpu_time(); // optionally initiating, to measure time from this point, // not from the script beginning // doing some stuff here echo cpu_time()." elapsed\n"; // doing yet some stuff here echo cpu_time()." elapsed\n"; 

In simple cases, it gives the same thing as microtime , but with less accuracy. The same function for microtime :

 function stopwatch(){ static $time=0; $prev=$time; $time=microtime(true); return $time-$prev; } 

Roughly, do not use like this:

 stopwatch(); f(); // some function, which calls `stopwatch` in itself too echo stopwatch(); 
0
source

Source: https://habr.com/ru/post/903278/


All Articles