Skip to content

Instantly share code, notes, and snippets.

@fallwith
Created November 17, 2022 23:47
Show Gist options
  • Save fallwith/c70299360d39201e427afd6475956a36 to your computer and use it in GitHub Desktop.
Save fallwith/c70299360d39201e427afd6475956a36 to your computer and use it in GitHub Desktop.
Ruby threads and fibers testing
#!/usr/bin/env ruby
# frozen_string_literal: true
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'async', '~> 2.2'
end
require 'async'
require 'async/scheduler'
class Tester
TIMES = 100_000
THREAD_COUNT = 3
def self.test_one
start = Time.now
work.call
puts "One run took #{Time.now - start}"
end
def self.test_threads
threads = []
start = Time.now
THREAD_COUNT.times { threads << Thread.new { work.call } }
threads.map(&:join)
puts "#{THREAD_COUNT} threads running took #{Time.now - start}"
end
def self.test_async
start = Time.now
THREAD_COUNT.times do
Async { work.call }
end
puts "#{THREAD_COUNT} jobs running via Async took #{Time.now - start}"
end
def self.test_async_scheduler
Fiber.set_scheduler(Async::Scheduler.new)
start = Time.now
Fiber.schedule do
THREAD_COUNT.times do
Fiber.schedule { work.call }
end
end
puts "#{THREAD_COUNT} jobs running via Async::Scheduler took #{Time.now - start}"
end
private
def self.work
@@work ||= -> { ::Tester::TIMES.times { 11 / 48 } }
end
if $PROGRAM_NAME == __FILE__
test_one
test_threads
test_async
test_async_scheduler
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment