3.0: added 'get_nvidia_data' common function

This commit is contained in:
Jordi Sanfeliu 2012-12-03 19:12:17 +01:00
parent d20c27520d
commit 932af01c27
1 changed files with 117 additions and 1 deletions

View File

@ -23,7 +23,7 @@ package Monitorix;
use strict;
use warnings;
use Exporter 'import';
our @EXPORT = qw(logger trim);
our @EXPORT = qw(logger trim get_nvidia_data);
sub logger {
my ($msg) = @_;
@ -40,4 +40,120 @@ sub trim {
return $str;
}
sub get_nvidia_data {
my ($gpu) = @_;
my $total = 0;
my $used = 0;
my $mem = 0;
my $cpu = 0;
my $temp = 0;
my $check_mem = 0;
my $check_cpu = 0;
my $check_temp = 0;
my $l;
open(IN, "nvidia-smi -q -i $gpu -d MEMORY,UTILIZATION,TEMPERATURE |");
my @data = <IN>;
close(IN);
for($l = 0; $l < scalar(@data); $l++) {
if($data[$l] =~ /Memory Usage/) {
$check_mem = 1;
next;
}
if($check_mem) {
if($data[$l] =~ /Total/) {
my (undef, $tmp) = split(':', $data[$l]);
if($tmp eq "\n") {
$l++;
$tmp = $data[$l];
}
my ($value, undef) = split(' ', $tmp);
$value =~ s/[-]/./;
$value =~ s/[^0-9.]//g;
if(int($value) > 0) {
$total = int($value);
}
}
if($data[$l] =~ /Used/) {
my (undef, $tmp) = split(':', $data[$l]);
if($tmp eq "\n") {
$l++;
$tmp = $data[$l];
}
my ($value, undef) = split(' ', $tmp);
$value =~ s/[-]/./;
$value =~ s/[^0-9.]//g;
if(int($value) > 0) {
$used = int($value);
}
$check_mem = 0;
}
}
if($data[$l] =~ /Utilization/) {
$check_cpu = 1;
next;
}
if($check_cpu) {
if($data[$l] =~ /Gpu/) {
my (undef, $tmp) = split(':', $data[$l]);
if($tmp eq "\n") {
$l++;
$tmp = $data[$l];
}
my ($value, undef) = split(' ', $tmp);
$value =~ s/[-]/./;
$value =~ s/[^0-9.]//g;
if(int($value) > 0) {
$cpu = int($value);
}
}
if($data[$l] =~ /Memory/) {
my (undef, $tmp) = split(':', $data[$l]);
if($tmp eq "\n") {
$l++;
$tmp = $data[$l];
}
my ($value, undef) = split(' ', $tmp);
$value =~ s/[-]/./;
$value =~ s/[^0-9.]//g;
if(int($value) > 0) {
$mem = int($value);
}
}
$check_cpu = 0;
}
if($data[$l] =~ /Temperature/) {
$check_temp = 1;
next;
}
if($check_temp) {
if($data[$l] =~ /Gpu/) {
my (undef, $tmp) = split(':', $data[$l]);
if($tmp eq "\n") {
$l++;
$tmp = $data[$l];
}
my ($value, undef) = split(' ', $tmp);
$value =~ s/[-]/./;
$value =~ s/[^0-9.]//g;
if(int($value) > 0) {
$temp = int($value);
}
}
$check_temp = 0;
}
}
# NVIDIA driver v285.+ not supported (needs new output parsing).
# This is to avoid a divide by zero message.
if($total) {
$mem = ($used * 100) / $total;
} else {
$mem = $used = $total = 0;
}
return join(" ", $mem, $cpu, $temp);
}
1;