|
| 1 | +#!/usr/bin/env ruby |
| 2 | +# frozen_string_literal: true |
| 3 | + |
| 4 | +# Released under the MIT License. |
| 5 | +# Copyright, 2026, by Shopify Inc. |
| 6 | +# Copyright, 2026, by Samuel Williams. |
| 7 | + |
| 8 | +require "async" |
| 9 | + |
| 10 | +module CountCancelCauses |
| 11 | + attr_accessor :for_calls |
| 12 | + |
| 13 | + def for(*arguments, **options, &block) |
| 14 | + self.for_calls ||= 0 |
| 15 | + self.for_calls += 1 |
| 16 | + |
| 17 | + super(*arguments, **options, &block) |
| 18 | + end |
| 19 | +end |
| 20 | + |
| 21 | +Async::Cancel::Cause.singleton_class.prepend(CountCancelCauses) |
| 22 | + |
| 23 | +def positive_integer(name, default) |
| 24 | + Integer(ENV.fetch(name, default)).tap do |value| |
| 25 | + abort("#{name} must be positive!") unless value.positive? |
| 26 | + end |
| 27 | +end |
| 28 | + |
| 29 | +def measure_cancel(total_tasks) |
| 30 | + scheduler = Async::Scheduler.new |
| 31 | + ready = Thread::Queue.new |
| 32 | + |
| 33 | + Fiber.set_scheduler(scheduler) |
| 34 | + |
| 35 | + begin |
| 36 | + total_tasks.times do |
| 37 | + scheduler.async do |
| 38 | + ready.push(true) |
| 39 | + sleep |
| 40 | + end |
| 41 | + end |
| 42 | + |
| 43 | + total_tasks.times do |
| 44 | + ready.pop |
| 45 | + end |
| 46 | + |
| 47 | + GC.start |
| 48 | + Async::Cancel::Cause.for_calls = 0 |
| 49 | + |
| 50 | + # Measure the synchronous fan-out only; draining cancelled tasks happens in `ensure`. |
| 51 | + allocated_before = GC.stat(:total_allocated_objects) |
| 52 | + start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC) |
| 53 | + |
| 54 | + scheduler.cancel |
| 55 | + |
| 56 | + duration = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time |
| 57 | + allocated_after = GC.stat(:total_allocated_objects) |
| 58 | + |
| 59 | + return { |
| 60 | + tasks: total_tasks, |
| 61 | + cause_for_calls: Async::Cancel::Cause.for_calls, |
| 62 | + allocated_objects: allocated_after - allocated_before, |
| 63 | + duration_ms: duration * 1000.0 |
| 64 | + } |
| 65 | + ensure |
| 66 | + scheduler.run unless scheduler.closed? |
| 67 | + Fiber.set_scheduler(nil) |
| 68 | + end |
| 69 | +end |
| 70 | + |
| 71 | +tasks = positive_integer("TASKS", 1365) |
| 72 | + |
| 73 | +result = measure_cancel(tasks) |
| 74 | + |
| 75 | +puts "tasks=#{result.fetch(:tasks)}" |
| 76 | +puts "cause_for_calls=#{result.fetch(:cause_for_calls)}" |
| 77 | +puts "allocated_objects=#{result.fetch(:allocated_objects)}" |
| 78 | +puts "duration_ms=#{format('%.2f', result.fetch(:duration_ms))}" |
0 commit comments