gpt4 book ai didi

windows - 如何获得计算机的平均 CPU/处理器使用率?

转载 作者:可可西里 更新时间:2023-11-01 09:26:31 25 4
gpt4 key购买 nike

现在我正在使用 PHP 和 Perl 开发一个程序来读取计算机的系统数据,并且我们一直在使用 SNMP 来收集数据(或者更确切地说,被迫)。检索数据后,我们应该将数据存储在数据库中,然后使用数据绘制折线图。

目前,我正在使用此 perl 脚本来检索计算机的 CPU/处理器使用情况。

  $MIB1 = ".1.3.6.1.2.1.25.3.3.1.2"; #Cpu Processors
$HOST = shift; #or localhost for testing

$count = 0;
#print out all the processors of the computer and their values
#SNMP is used with perl because of the libraries
#snmpwalk retrieves information from the computers by the computer name and MIB
#as there are many values, they are stored in an array to be used
(@values) = &snmpwalk("$HOST","$MIB1");
foreach $value (@values)
{
$count++;
if ($value) {
#fixes the value for presentation
$goodvalue = &strip_comment($value);
#prints out the result. $count will count out the processor number
print "CPU Usage of Processor $count: $goodvalue%\n"; }
if ($value > 90){
#warns user if the processor usage is over 90%
print "Warning: CPU Usage over 90%! \n"
}
else { warn "No response from host :$HOST:\n"; } #provides error
}

代码,或者更确切地说,SNMP 检索几个单独的处理器,许多人应该知道一台计算机上可以有多个处理器,因此将这些数据存储到数据库中不太实用,(例如,如果一台计算机只有 2 个处理器,下一个有 4 个,房间对面的那个有 100 个。)

所以我想知道是否有人可以帮助改进此代码或更改它,以便我可以将它们全部加在一起,找到 CPU/处理器使用率的平均值并将其存储到数据库中。因为,我不太确定如何去做,因为循环一次只扫描 1 个处理器,而且可能不知道有多少个处理器。

提前致谢。

最佳答案

以host和cpu号为双键,a group by取平均值。

这是一个使用 sqlite3 的例子。

首先创建表:

CREATE TABLE cpu (host string, cpu integer, load integer, primary key (host, cpu));

然后插入一些测试数据(这将由您的 perl 脚本完成):

INSERT INTO cpu (host, cpu, load) VALUES ("appserv", 1, 25);
INSERT INTO cpu (host, cpu, load) VALUES ("appserv", 2, 15);
INSERT INTO cpu (host, cpu, load) VALUES ("dbserv", 1, 10);
INSERT INTO cpu (host, cpu, load) VALUES ("dbserv", 2, 30);
INSERT INTO cpu (host, cpu, load) VALUES ("dbserv", 3, 5);
INSERT INTO cpu (host, cpu, load) VALUES ("dbserv", 4, 5);

现在您可以获得每个主机的平均负载,可以使用 PHP 检索和绘制:

SELECT host, avg(load) FROM cpu GROUP BY host;

appserv|20.0
dbserv|12.5

所有主机的总平均值:

SELECT avg(load) FROM cpu;

15.0

或者找到任何高负载的主机:

SELECT host FROM cpu WHERE load > 25;

dbserv

您可能想要创建一个包含所有计算机的表并将其链接到上面的 cpu 表,用 computer_id 交换主机字符串。

所有这些都假设您使用的是关系数据库(即 SQLite、MySQL、Oracle 等)。

关于windows - 如何获得计算机的平均 CPU/处理器使用率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3528134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com