JRuby线程性能

时间:2014-04-09 15:10:05

标签: multithreading jruby gil

我编写了一个脚本来测试JRuby的多线程性能。这个脚本在4核机器和其他机器上运行,我一直得到令人失望的结果。这是脚本和结果。有人可以看看脚本是否有问题或解释为什么会发生这种情况?我认为,由于对全局解释器锁的依赖性较小(或没有),多线程性能应该优于此。

class TestThread
    def calc(times)
        sum = 0;
        0.upto(times) do
            sum = (sum + 19327437) % 234978
        end
        sum
    end

    def single(times)
        time1 = Time.now
        sum = calc(times)
        time2 = Time.now
    end
end

class ThreadInvoker
    def ThreadInvoker.run(times, num_threads)
        objs = []
        threads = []

        time1 = Time.now
        num_threads.times do |n|
            obj = TestThread.new
            objs << obj
            threads << Thread.new do
                obj.single(times)
            end
        end
        threads.map(&:join)
        time2 = Time.now
        puts "#{num_threads} threads. Time elapsed #{(time2 - time1)*1000} milliseconds."
    end
end

# test = TestThread.new
ThreadInvoker.run(30000000, 1)
ThreadInvoker.run(30000000, 3)
ThreadInvoker.run(30000000, 1)
ThreadInvoker.run(30000000, 3)
ThreadInvoker.run(30000000, 1)
ThreadInvoker.run(30000000, 3)

这是结果,单线程交错与多线程。请注意,多线程性能始终是单个线程所需时间的两倍:

1 threads. Time elapsed 3292.0 milliseconds.
3 threads. Time elapsed 6880.0 milliseconds.
1 threads. Time elapsed 2995.0 milliseconds.
3 threads. Time elapsed 7270.0 milliseconds.
1 threads. Time elapsed 3120.0 milliseconds.
3 threads. Time elapsed 7613.0 milliseconds.

*已修改为将puts带出线程

0 个答案:

没有答案