File Coverage

blib/lib/Sys/Simple/CPU/Linux.pm
Criterion Covered Total %
statement 33 33 100.0
branch n/a
condition 3 4 75.0
subroutine 5 5 100.0
pod 0 1 0.0
total 41 43 95.3


line stmt bran cond sub pod time code
1             package Sys::Simple::CPU::Linux;
2              
3 2     2   494 use strict;
  2         3  
  2         46  
4 2     2   5 use warnings;
  2         2  
  2         42  
5              
6 2     2   925 use IO::Handle;
  2         8929  
  2         78  
7 2     2   871 use Time::HiRes qw/usleep/;
  2         1934  
  2         6  
8              
9              
10             # cpu usage: Get cpu usage on perl,
11             # based on this post on stackoverflow
12             #
13             # Sleep to give the /proc time to update
14             #
15             # https://stackoverflow.com/questions/23367857/accurate-calculation-of-cpu-usage-given-in-percentage-in-linux/23376195#23376195
16             #
17              
18             my @fields = qw/tag user nice system idle iowait irq softirq steal guest guest_nice/;
19              
20             sub cpu_usage {
21 4   100 4 0 560 my $factor = $_[0] || 1;
22 4         9 my $wait = 10_000 * $factor;
23              
24 4         6 my %previous;
25             my %actual;
26              
27             # I like to ident after the open when doing "block" operation
28             # over the contents of a file handle
29              
30 4         143 open my $fh, "<", "/proc/stat";
31 4         21 $fh->autoflush( 1 );
32 4         443 @previous{ @fields } = split ( /\s+/, <$fh> );
33              
34 4         220436 usleep $wait;
35 4         309 seek $fh, 0, 0;
36              
37 4         43 $fh->autoflush( 1 );
38 4         570 @actual{ @fields } = split ( /\s+/, <$fh> );
39 4         308 close $fh;
40            
41 4         23 my $previdle = $previous{ idle } + $previous{ iowait };
42 4         13 my $idle = $actual{ idle } + $actual{ iowait };
43            
44             my $prevnonidle = $previous{ user } + $previous{ nice }
45             + $previous{ system } + $previous{ irq }
46 4         19 + $previous{ softirq } + $previous{ steal };
47            
48             my $nonidle = $actual{ user } + $actual{ nice }
49             + $actual{ system } + $actual{ irq }
50 4         15 + $actual{ softirq } + $actual{ steal };
51            
52 4         7 my $prevtotal = $previdle + $prevnonidle;
53 4         13 my $total = $idle + $nonidle;
54            
55 4         11 my $totald = $total - $prevtotal;
56 4         6 my $idled = $idle - $previdle;
57            
58 4   50     23 my $cpu_percentage = ( $totald - $idled ) / ( $totald || 1 );
59            
60 4         79 return $cpu_percentage;
61            
62             }
63              
64             1;