Skip to content

Instantly share code, notes, and snippets.

@mamemomonga
Created January 15, 2021 12:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mamemomonga/cc49f76fdea820297bd4133a38b207c2 to your computer and use it in GitHub Desktop.
Save mamemomonga/cc49f76fdea820297bd4133a38b207c2 to your computer and use it in GitHub Desktop.
LinuxのCPU(全コア)の使用率を表示する。
#!/usr/bin/env perl
use strict;
use warnings;
use feature 'say';
use Time::HiRes 'usleep';
sub get_cpu_stat {
my $stat='';
open(my $fh,'<','/proc/stat') || die $!;
local $/; $stat=<$fh>;
my ($user,$nice,$system,$idle)=($1,$2,$3,$4) if ($stat=~/cpu\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+/);
return $user+$nice+$system,$idle;
}
while(1){
my ($cput1,$idle1)=get_cpu_stat();
usleep(500*1000);
my ($cput2,$idle2)=get_cpu_stat();
my $cput3=$cput2-$cput1;
my $idle3=$idle2-$idle1;
my $cpup=($cput3 / ($cput3+$idle3))*100;
say sprintf('% 8.2f%%',$cpup);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment