summaryrefslogtreecommitdiff
path: root/test/fiber/http.rb
blob: ad51ae3c769f9d994ce1eccf75e12469b762650c (plain)
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

require 'benchmark'

TOPICS = ["cats", "dogs", "pigs", "skeletons", "zombies", "ocelots", "villagers", "pillagers"]

require 'net/http'
require 'uri'
require 'json'

require_relative 'scheduler'

def fetch_topics(topics)
  responses = {}

  topics.each do |topic|
    Fiber.new(blocking: Fiber.current.blocking?) do
      uri = URI("https://www.google.com/search?q=#{topic}")
      responses[topic] = Net::HTTP.get(uri).scan(topic).size
    end.resume
  end

  Thread.fiber_scheduler&.run

  return responses
end

def sweep(repeats: 3, **options)
  times = (1..8).map do |i|
    $stderr.puts "Measuring #{i} topic(s)..."
    topics = TOPICS[0...i]

    Thread.new do
      Benchmark.realtime do
        scheduler = Scheduler.new
        Fiber.set_scheduler scheduler

        repeats.times do
          Fiber.new(**options) do
            pp fetch_topics(topics)
          end.resume

          scheduler.run
        end
      end
    end.value / repeats
  end

  puts options.inspect
  puts JSON.dump(times.map{|value| value.round(3)})
end

sweep(blocking: true)
sweep(blocking: false)