-
Notifications
You must be signed in to change notification settings - Fork 0
/
fiber_blog_post.rb
executable file
·67 lines (54 loc) · 1.19 KB
/
fiber_blog_post.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/usr/bin/env ruby
# asynchronous - using blocking Fiber primitive
def nap
# puts "you now have to wait, while I nap..."
sleep 3
# puts "...and now I'm awake, you can move along."
end
puts "blocking asynchronous execution, using the Fiber primitive"
fiber = Fiber.new do
nap
nap
end
fiber.resume
puts "blocking fibers are so boring."
# asynchronous - non-blocking fiber using Async gem
require 'async'
def nap_async
Async do |task|
# puts "you now have to wait, while I nap..."
sleep 3
# puts "...and now I'm awake, you can move along."
end
end
puts "non-blocking asynchronous execution, using the Async gem"
Async do
nap_async
nap_async
end
puts "non-blocking fibers are so much fun!"
# benchmark
require 'benchmark'
Benchmark.bm do |x|
# sequential version
x.report('sequential'){ 3.times{ nap } }
# blocking fiber version
x.report('blocking fiber'){
3.times.map do
fiber = Fiber.new do
nap
end
fiber.resume
end
}
# non-blocking fiber version
x.report('non-blocking fiber'){
Async do
3.times.map do
Async do
nap_async
end
end
end
}
end