File: write_vs_write_nonblock.rb

package info (click to toggle)
ruby-bunny 2.9.2-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 1,324 kB
  • sloc: ruby: 9,559; sh: 28; makefile: 6
file content (49 lines) | stat: -rw-r--r-- 922 bytes parent folder | download | duplicates (5)
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
#!/usr/bin/env ruby

require "benchmark"

# This tests demonstrates throughput difference of
# IO#write and IO#write_nonblock. Note that the two
# may not be equivalent depending on your

r, w = IO.pipe

# buffer size
b    = 65536

read_loop = Thread.new do
  loop do
    begin
      r.read_nonblock(b)
    rescue Errno::EWOULDBLOCK, Errno::EAGAIN => e
      IO.select([r])
      retry
    end
  end
end

n = 10_000
# 7 KB
s = "a" * (7 * 1024)
Benchmark.bm do |meter|
  meter.report("write:") do
    n.times { w.write(s.dup) }
  end
  meter.report("write + flush:") do
    n.times { w.write(s.dup); w.flush }
  end
  meter.report("write_nonblock:") do
    n.times do
      s2 = s.dup
      begin
        while !s2.empty?
          written = w.write_nonblock(s2)
          s2.slice!(0, written)
        end
      rescue Errno::EWOULDBLOCK, Errno::EAGAIN
        IO.select([], [w])
        retry
      end
    end
  end
end