Skip to content

Instantly share code, notes, and snippets.

@nicholaspufal
Last active January 12, 2022 02:27
Show Gist options
  • Save nicholaspufal/608a5dad4de7bfaed6f250fc16924330 to your computer and use it in GitHub Desktop.
Save nicholaspufal/608a5dad4de7bfaed6f250fc16924330 to your computer and use it in GitHub Desktop.
Ruby 3.1.0 Benchmarks

Script

# foo.rb
def execute_high_cpu_task
  1000.times do
    10 ** 999999
  end
end

threads = []
if ARGV[0] == "threads"
  puts "running PID #{Process.pid}"
  4.times do
    threads << Thread.new { execute_high_cpu_task }
  end
  threads.each(&:join)
  puts 'finished threads'
else
  puts "running PID #{Process.pid}"
  4.times do
    threads << Ractor.new { execute_high_cpu_task }
  end
  threads.each(&:take)
  puts 'finished ractors'
end

Results

Ractors

$ time ruby foo.rb
running PID 44779
real    0m13.845s

# Showing main process and threads
$ ps M 44779
USER     PID   TT   %CPU STAT PRI     STIME     UTIME COMMAND
npufal 44779 s004    0.0 S    31T   0:00.02   0:00.06 ruby foo.rb
       44779         0.0 S    31T   0:00.00   0:00.00
       44779        85.3 R    31T   0:00.73   0:09.97
       44779        86.7 R    31T   0:00.72   0:09.91
       44779        87.1 R    31T   0:00.74   0:09.77
       44779        82.8 R    31T   0:00.73   0:09.61
# ^ many with STAT R (running at the same time), high CPU usage per thread

Threads

$ time ruby foo.rb threads
running PID 45370
real    0m44.915s

# Showing main process and threads
$ ps M 45370
USER     PID   TT   %CPU STAT PRI     STIME     UTIME COMMAND
npufal 45370 s004    0.0 S    31T   0:00.02   0:00.06 ruby foo.rb threads
       45370         0.0 S    31T   0:00.00   0:00.00
       45370        29.3 S    31T   0:00.13   0:01.33
       45370        33.6 S    31T   0:00.11   0:01.32
       45370        14.4 R    31T   0:00.12   0:01.25
       45370        20.6 S    31T   0:00.10   0:01.23
# ^ only one with STAT R (running at the same time), low CPU usage per thread
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment