Skip to content

Instantly share code, notes, and snippets.

@Watson1978
Forked from ekmartin/rmagick_test.rb
Created September 28, 2026 04:31
Show Gist options
  • Select an option

  • Save Watson1978/9345ae89017e2b520c5b4bfde167f242 to your computer and use it in GitHub Desktop.

Select an option

Save Watson1978/9345ae89017e2b520c5b4bfde167f242 to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
# Runs JOBS concurrent "decode 12MP JPEG -> quantize(2) -> Group4 TIFF" jobs in
# one Async reactor and reports wall time and the longest time the reactor was
# unable to run a 10ms ticker fiber.
#
# gem install async # Ruby 4.0; async >= 2.26 for IO::Event::WorkerPool
# MAGICK_THREAD_LIMIT=1 ruby offload_benchmark.rb # no worker pool
# MAGICK_THREAD_LIMIT=1 WORKERS=1 ruby offload_benchmark.rb # 1-thread pool
# MAGICK_THREAD_LIMIT=1 WORKERS=4 ruby offload_benchmark.rb # 4-thread pool
#
# MAGICK_THREAD_LIMIT=1 keeps ImageMagick's own OpenMP threads out of the
# picture, so the wall-time difference comes only from the worker pool.
require 'async'
require 'rmagick'
WORKERS = Integer(ENV.fetch('WORKERS', '0'))
JOBS = Integer(ENV.fetch('JOBS', '4'))
def monotonic = Process.clock_gettime(Process::CLOCK_MONOTONIC)
# A 12 megapixel JPEG with photo-like entropy, generated once.
photo = Magick::Image.read('plasma:fractal') { |options| options.size = '4000x3000' }.first
BLOB = photo.to_blob do |options|
options.format = 'JPEG'
options.quality = 90
end
photo.destroy!
def job
Magick::Image.from_blob(BLOB).first.quantize(2).to_blob do |options|
options.format = 'TIFF'
options.compression = Magick::Group4Compression
end
end
worker_pool = WORKERS.positive? ? IO::Event::WorkerPool.new(maximum_worker_count: WORKERS) : nil
Fiber.set_scheduler(Async::Scheduler.new(worker_pool: worker_pool))
longest_stall = 0.0
started = monotonic
Async do |task|
ticker = task.async do
last = monotonic
loop do
sleep(0.01)
now = monotonic
longest_stall = [longest_stall, now - last].max
last = now
end
end
JOBS.times.map { task.async { job } }.each(&:wait)
ticker.stop
end
Fiber.set_scheduler(nil)
printf("%-24s %d jobs, %.1f MB JPEG: wall %.2fs, longest reactor stall %.2fs\n",
WORKERS.positive? ? "worker pool (#{WORKERS} threads)" : 'no worker pool',
JOBS, BLOB.bytesize / 1e6, monotonic - started, longest_stall)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment