Skip to content

Commit

Permalink
Merge pull request #8 from j8r/each_use
Browse files Browse the repository at this point in the history
Add an `each_use` loop
  • Loading branch information
bararchy authored Apr 27, 2018
2 parents d6c3d0d + e070c33 commit 3e3c90a
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 9 deletions.
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ Returns a NamedTuple including the used, idle and total CPU time.

Returns the cpu used in percentage in the last `sleep_time` seconds.

`.each_use(sleep_time = 1) : Int32`

Returns the cpu used in percentage each `sleep_time` seconds infinitely.

#### Methods included in the `Hardware::Memory` struct:

`.new`
Expand Down Expand Up @@ -64,7 +68,9 @@ memory.used #=> 2731404
memory.percent #=> 32
Hardware::CPU.used #=> 12
Hardware::CPU.each_use do |cpu|
cpu #=> 17
end
```

## Development
Expand Down
7 changes: 7 additions & 0 deletions spec/cpu_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,11 @@ describe Hardware::CPU do
it "checks the percentage used" do
(0 <= Hardware::CPU.used <= 100).should be_true
end

it "checks the percentage in each_use" do
Hardware::CPU.each_use do |cpu|
(0 <= cpu <= 100).should be_true
break
end
end
end
4 changes: 2 additions & 2 deletions src/hardware.cr
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
require "./hardware/*"
require "./hardware/**"

module Hardware
VERSION = "0.2.1"
VERSION = "0.2.2"
end
19 changes: 13 additions & 6 deletions src/hardware/cpu.cr
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,19 @@ module Hardware::CPU
}
end

def self.used(sleep_time = 1)
proc0 = info
sleep sleep_time
proc1 = info
def self.each_use(sleep_time = 1)
proc_last = info
loop do
sleep sleep_time
proc_now = info

# 100 * Usage / Total
yield (100 * ((proc_now[:used] - proc_last[:used]).to_f32 / (proc_now[:total] - proc_last[:total]))).round
proc_last = proc_now
end
end

# 100 * Usage / Total
(100 * ((proc1[:used] - proc0[:used]).to_f32 / (proc1[:total] - proc0[:total]))).round
def self.used(sleep_time = 1)
each_use(sleep_time) { |cpu| return cpu }
end
end

0 comments on commit 3e3c90a

Please sign in to comment.