PHP obtains real-time CPU memory usage in Windows environment
这篇文章主要介绍了php在windows环境下获得 cpu 内存实时使用率的相关资料,非常不错,具有参考和学习PHP的价值,对PHP感兴趣的朋友可以参考下本篇文章
后台实时监控服务器的CUP与内存占用率的场景很常见,虽然没做过,但是着手写代码之前我真没想到会花2个多小时才最终实现。
网上虽然搜 PHP CUP 内存 使用率 这一类关键字出来的文章一大把,但大都是在Linux环境下,windows下只有提出靠cmd语句实现的观点,但少有实际直接可行的代码,辗转试了一遍 wmic , systeminfo 各种并不熟稔的cmd命令,并没有找到可行的方案,最终通过百度知道 的一篇答案找到利用vbs获取的实现方式,稍加改善,可以在windows环境下直接使用。
类代码
class SystemInfoWindows { /** * 判断指定路径下指定文件是否存在,如不存在则创建 * @param string $fileName 文件名 * @param string $content 文件内容 * @return string 返回文件路径 */ private function getFilePath($fileName, $content) { $path = dirname(FILE) . "\\$fileName"; if (!file_exists($path)) { file_put_contents($path, $content); } return $path; } /** * 获得cpu使用率vbs文件生成函数 * @return string 返回vbs文件路径 */ private function getCupUsageVbsPath() { return $this->getFilePath( 'cpu_usage.vbs', "On Error Resume Next Set objProc = GetObject(\"winmgmts:\\\\.\\root\cimv2:win32_processor='cpu0'\") WScript.Echo(objProc.LoadPercentage)" ); } /** * 获得总内存及可用物理内存JSON vbs文件生成函数 * @return string 返回vbs文件路径 */ private function getMemoryUsageVbsPath() { return $this->getFilePath( 'memory_usage.vbs', "On Error Resume Next Set objWMI = GetObject(\"winmgmts:\\\\.\\root\cimv2\") Set colOS = objWMI.InstancesOf(\"Win32_OperatingSystem\") For Each objOS in colOS Wscript.Echo(\"{\"\"TotalVisibleMemorySize\"\":\" & objOS.TotalVisibleMemorySize & \",\"\"FreePhysicalMemory\"\":\" & objOS.FreePhysicalMemory & \"}\") Next" ); } /** * 获得CPU使用率 * @return Number */ public function getCpuUsage() { $path = $this->getCupUsageVbsPath(); exec("cscript -nologo $path", $usage); return $usage[0]; } /** * 获得内存使用率数组 * @return array */ public function getMemoryUsage() { $path = $this->getMemoryUsageVbsPath(); exec("cscript -nologo $path", $usage); $memory = json_decode($usage[0], true); $memory['usage'] = Round((($memory['TotalVisibleMemorySize'] - $memory['FreePhysicalMemory']) / $memory['TotalVisibleMemorySize']) * 100); return $memory; } }
调用方式
$info = new SystemInfoWindows(); $cpu = $info->getCpuUsage(); $memory = $info->getMemoryUsage(); echo "当前系统CPU使用率:{$cpu}%,内存使用率{$memory['usage']}%";
总结
以上所述是小编给大家介绍的php在windows环境下获得cpu内存实时使用率,希望对大家有所帮助!!
PHP相关推荐:
前面我们和大家分享了php和redis实现商城秒杀功能代码分享,本文主要为大家详细介绍......
本文主要和大家详细介绍了php处理抢购类功能的高并发请求,具有一定的参考价值......
本文主要给大家介绍了关于由php中字符offset特征造成的绕过漏洞的相关资料,文中不仅......
购物车类 Cookies 保存,保存周期为1天 注意:浏览器必须支持Cookie才能够使用。本文......
The above is the detailed content of PHP obtains real-time CPU memory usage in Windows environment. For more information, please follow other related articles on the PHP Chinese website!

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version
Chinese version, very easy to use

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver Mac version
Visual web development tools
