I need to figure out how much RAM/CPU a particular Laravel app is using, but so far the current code shows the entire system's usage.
How can I, instead, check how much RAM/CPU only one Laravel app is using? (kind of how the Windows task manager shows each program's CPU/RAM usage- but for web apps instead [particularly Laravel, but vanilla PHP solutions are welcome])
Current code below...
web.php:
...
Route::get('/details', function () {
//RAM usage
$free = shell_exec('free');
$free = (string) trim($free);
$free_arr = explode("\n", $free);
$mem = explode(" ", $free_arr[1]);
$mem = array_filter($mem);
$mem = array_merge($mem);
$usedmem = $mem[2];
$usedmemInGB = number_format($usedmem / 1048576, 2) . ' GB';
$memory1 = $mem[2] / $mem[1] * 100;
$memory = round($memory1) . '%';
$fh = fopen('/proc/meminfo', 'r');
$mem = 0;
while ($line = fgets($fh)) {
$pieces = array();
if (preg_match('/^MemTotal:\s (\d )\skB$/', $line, $pieces)) {
$mem = $pieces[1];
break;
}
}
fclose($fh);
$totalram = number_format($mem / 1048576, 2) . ' GB';
//cpu usage
$cpu_load = sys_getloadavg();
$load = $cpu_load[0] . '% / 100%';
return view('details',compact('memory','totalram','usedmemInGB','load'));
});
...
details.blade.php:
<html>
<head>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div >
<h2 >Current RAM Usage</h2>
<div >
<div style="width: {{$memory}}">
<span >{{$memory}}</span>
</div>
</div>
<span >{{$usedmemInGB}} / {{$totalram}} ({{$memory}})</span>
</div>
<div >
<h2 >Current CPU Usage</h2>
<div >
<div style="width: {{$load}}">
<span >{{$load}}</span>
</div>
</div>
<span >{{$load}}</span>
</div>
</body>
</html>
CodePudding user response:
Do not use Laravel to detect how much resources is Laravel consuming from your server resources, instead I would use server monitoring tools.
htop
Is a very good command that we can use to detect what apps are using our server the most and how much!
Now if you are good with servers, I advise you to use
CodePudding user response:
You could get the memory usage of you web server thread, not exactly what you need but very close.
Suppose you use linux system (tested on my CentOS7 XAMPP environment):
$pid = getmypid();
exec("ps -eo%mem,rss,pid | grep $pid", $output);
$output = explode(" ", $output[0]);
dd($output[1]); // result in kB
For windows (tested on my Win10 XAMPP environment):
$output = array();
exec( 'tasklist /FI "PID eq ' . getmypid() . '" /FO LIST', $output );
dd($output[5]); // result in kB