Skip to content

Instantly share code, notes, and snippets.

@neerajsingh0101
Last active May 17, 2025 19:45
Show Gist options
  • Save neerajsingh0101/377d523a4c89804a71aa6cf479ac17ca to your computer and use it in GitHub Desktop.
Save neerajsingh0101/377d523a4c89804a71aa6cf479ac17ca to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
require 'bundler/inline'
require 'benchmark'
gemfile do
source 'https://rubygems.org'
gem 'gvl-tracing'
gem 'parallel'
end
def cpu_intensive(n)
result = 0
n.times do |i|
n.times do |j|
result += i * j
end
end
result
end
def benchmark(thread_count, type, &block)
puts "\nStarting demo with #{thread_count} threads doing #{type} work"
time = Benchmark.realtime do
Parallel.each(Array.new(8) { |i| [i] },
in_threads: thread_count) do |chunk|
yield
end
end
puts "Time elapsed: #{time.round(4)} seconds"
end
puts "Running demonstrations with GVL tracing..."
GvlTracing.start("cpu_bound_single.json") do
benchmark(1, 'CPU-bound') { cpu_intensive(5000) }
end
GvlTracing.start("cpu_bound_multi.json") do
benchmark(3, 'CPU-bound') { cpu_intensive(5000) }
end
def mixed_workload(n)
sleep(0.05)
cpu_intensive(n)
end
GvlTracing.start("mixed_single.json") do
benchmark(1, 'Mixed I/O and CPU') { mixed_workload(5000) }
end
GvlTracing.start("mixed_multi.json") do
benchmark(3, 'Mixed I/O and CPU') { mixed_workload(5000) }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment