How To Check Usage of RAM And CPU In Laravel
Hello All,
In this small tutorial, I will show you How To Check RAM And CPU usage In Laravel in ubuntu OS. many times we require to check how much RAM and CPU usage of consumption in the server if we do not have the code then we need to check manually every time, so here I will give you an example with code So you can get data of RAM and CPU usage in your admin panel.
So Create a controller and add a function for this example.
public function total_ram_cpu_usage()
{
<span class="hljs-comment">//RAM usage</span>
$free = shell_exec(<span class="hljs-string">'free'</span>);
$free = (string) trim($free);
$free_arr = explode(<span class="hljs-string">"\n"</span>, $free);
$mem = explode(<span class="hljs-string">" "</span>, $free_arr[<span class="hljs-number">1</span>]);
$mem = array_filter($mem);
$mem = array_merge($mem);
$usedmem = $mem[<span class="hljs-number">2</span>];
$usedmemInGB = number_format($usedmem / <span class="hljs-number">1048576</span>, <span class="hljs-number">2</span>) . <span class="hljs-string">' GB'</span>;
$memory1 = $mem[<span class="hljs-number">2</span>] / $mem[<span class="hljs-number">1</span>] * <span class="hljs-number">100</span>;
$memory = round($memory1) . <span class="hljs-string">'%'</span>;
$fh = fopen(<span class="hljs-string">'/proc/meminfo'</span>, <span class="hljs-string">'r'</span>);
$mem = <span class="hljs-number">0</span>;
<span class="hljs-keyword">while</span> ($line = fgets($fh)) {
$pieces = <span class="hljs-keyword">array</span>();
<span class="hljs-keyword">if</span> (preg_match(<span class="hljs-string">'/^MemTotal:\s+(\d+)\skB$/'</span>, $line, $pieces){
$mem = $pieces[<span class="hljs-number">1</span>];
<span class="hljs-keyword">break</span>;
}
}
fclose($fh);
$totalram = number_format($mem / <span class="hljs-number">1048576</span>, <span class="hljs-number">2</span>) . <span class="hljs-string">' GB'</span>;
<span class="hljs-comment">//cpu usage</span>
$cpu_load = sys_getloadavg();
$load = $cpu_load[<span class="hljs-number">0</span>] . <span class="hljs-string">'% / 100%'</span>;
<span class="hljs-keyword">return</span> view(<span class="hljs-string">'details'</span>,compact(<span class="hljs-string">'memory'</span>,<span class="hljs-string">'totalram'</span>,<span class="hljs-string">'usedmemInGB'</span>,<span class="hljs-string">'load'</span>));
}
And you will now get the current usage of RAM and CPU.