3
N.times { Thread.new { puts Benchmark.measure { /* code */ } } }

基准测试是否显示了在线程中执行代码实际花费的时间?

或者它是否显示 ruby​​ 解释器在我们正在考虑的线程处于活动状态时在任何线程上运行的总时间(即使它因为另一个正在运行而暂停)?

例如假设线程 A 已经执行了 1ms,然后 MRI 切换到线程 B 并在那里停留了 3ms。最后线程 A 再次执行,再过 1ms 后终止。

对于线程 A,基准测试显示总时间为 2 毫秒还是 5 毫秒?(不是实时的)

更新:我认为单个 Sidekiq 进程会产生多个 Ruby 线程。所以就相当于说 Sidekiq 作业而不是线程。当 Sidekiq 执行其他一些繁重的工作时,我有一些 Sidekiq 工作需要更多的cpu 时间。这使我认为基准测试包括花在其他工作上的时间。然而,也许@mudasobwa 是对的,cpu 时间不包括花在其他线程/作业上的时间。在这种情况下,我能给出的唯一解释是系统连接/带宽是一个瓶颈(我的轻量级作业性能受到其他消耗大量带宽的繁重作业的影响)。

4

1 回答 1

1

我想知道是不是很难检查?

▶ Benchmark.measure { 3.times { |i| 
    Thread.new { puts Benchmark.measure { sleep i }.inspect } 
  } }
#⇒ #<Benchmark::Tms:0x000000018c2818 @label="", @real=8.5858e-05, @cstime=0.0, @cutime=0.0, @stime=0.0, @utime=0.0, @total=0.0>
#⇒ #<Benchmark::Tms:0x000000018c3ab0 @cstime=0.0, @cutime=0.0, @label="", @real=0.000118425, @stime=0.0, @total=0.0, @utime=0.0>
#⇒ #<Benchmark::Tms:0x0000000183cc40 @label="", @real=1.000119122, @cstime=0.0, @cutime=0.0, @stime=0.0, @utime=0.0, @total=0.0>
#⇒ #<Benchmark::Tms:0x0000000183c7e0 @label="", @real=2.000088775, @cstime=0.0, @cutime=0.0, @stime=0.0, @utime=0.0, @total=0.0>

第二行显然是周围的总数。

好的,这是一个唤醒线程的示例(最后是总数):

▶ Benchmark.measure { 3.times { |i| Thread.new { puts Benchmark.measure { (i * 100_000_000).times { 2000 << 2 } }.inspect } } }
#⇒ #<Benchmark::Tms:0x000000016c6438 @label="", @real=2.377e-06, @cstime=0.0, @cutime=0.0, @stime=0.0, @utime=0.0, @total=0.0>
#⇒ #<Benchmark::Tms:0x000000016c5420 @label="", @real=9.034328202, @cstime=0.0, @cutime=0.0, @stime=0.0, @utime=9.040000000000001, @total=9.040000000000001>
#⇒ #<Benchmark::Tms:0x000000016c4a98 @label="", @real=13.769757073, @cstime=0.0, @cutime=0.0, @stime=0.010000000000000009, @utime=13.77, @total=13.78>
#⇒ #<Benchmark::Tms:0x000000016c6bb8 @cstime=0.0, @cutime=0.0, @label="", @real=5.1321e-05, @stime=0.0, @total=0.0, @utime=0.0>
于 2016-06-23T13:00:20.227 回答