1

我编写了一个脚本来测试 JRuby 的多线程性能。该脚本在 4 核机器和其他机器上运行,我一直得到令人失望的结果。这是脚本和结果。有人可以看看脚本是否有问题或解释为什么会这样吗?我认为在对 Global Interpreter Lock 的依赖较少(或不依赖)的情况下,多线程性能应该比这更好。

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退出线程

4

0 回答 0