4

SOに関する私の最初の質問ですが、私は長い間潜んでいたので、ルールを破ったり、ゴミの質問を投稿したりした場合は、私を許してください.

私はスレッド化をよりよく理解しようとしており、MRI をテストして、一般的なパフォーマンスを確認することにしました。

次のコード (および出力) を考えると、スレッド化された操作がスレッド化されていないバリアントよりもはるかに遅いのはなぜですか?

コード

class Benchmarker
  def self.go
    puts '----------Benchmark Start----------'
    start_t = Time.now
    yield
    end_t = Time.now
    puts "Operation Took: #{end_t - start_t} seconds"
    puts '----------Benchmark End------------'
  end
end

# using mutex
puts 'Benchmark 1 (threaded, mutex):'
Benchmarker.go do
  array = []
  mutex = Mutex.new
  5000.times.map do
    Thread.new do
      mutex.synchronize do
        1000.times do
          array << nil
        end
      end
    end
  end.each(&:join)
  puts array.size
end

# using threads
puts 'Benchmark 2 (threaded, no mutex):'
Benchmarker.go do
  array = []
  5000.times.map do
    Thread.new do
      1000.times do
        array << nil
      end
    end
  end.each(&:join)
  puts array.size
end

# no threads
puts 'Benchmark 3 (no threads):'
Benchmarker.go do
  array = []
  5000.times.map do
    1000.times do
      array << nil
    end
  end
  puts array.size
end

出力

Benchmark 1 (threaded, mutex):
----------Benchmark Start----------
5000000
Operation Took: 3.373886 seconds
----------Benchmark End------------
Benchmark 2 (threaded, no mutex):
----------Benchmark Start----------
5000000
Operation Took: 5.040501 seconds
----------Benchmark End------------
Benchmark 3 (no threads):
----------Benchmark Start----------
5000000
Operation Took: 0.454665 seconds
----------Benchmark End------------

前もって感謝します。

4

1 に答える 1