为何Threads.@spawn与Threads.@threads执行耗时存在差异?
为什么
Threads.@threads比@sync + Threads.@spawn执行耗时更长? 我测试了两段多线程代码,用julia -t4 test.jl执行后,发现withthreads()函数的执行耗时比withsync()长得多,原本预期两者耗时应该一致,想知道原因。
测试代码如下:
function withthreads() arr = zeros(Int, 10) Threads.@threads for i in 1:10 # sleep(3 * rand()) sleep(1) arr[i] = i end println("with @threads: $arr") end function withsync() arr = zeros(Int, 10) @sync begin for i in 1:10 Threads.@spawn begin # sleep(3 * rand()) sleep(1) arr[i] = i end end end println("with @sync: $arr") end @time withthreads() @time withsync()
执行后输出:
with @threads: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 3.174835 seconds (18.51 k allocations: 1.072 MiB, 2.52% compilation time) with @sync: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 1.035465 seconds (1.40 k allocations: 75.718 KiB, 1.28% compilation time)
内容的提问来源于stack exchange,提问作者Yi Wangtian
相关产品推荐
相关产品推荐

