Skip to content

Commit 26b7cdc

Browse files
committed
Fast-track @threads when nthreads() == 1
This avoids overhead when threading is disabled, Example benchmark: ``` using BenchmarkTools, Base.Threads function func(val) local sum = 0 for idx in 1:100 sum += idx.^val end return sum end function func_threaded(val) local sum = 0 @threads for idx in 1:100 sum += idx.^val end return sum end @show @benchmark func(2.0) @show @benchmark func_threaded(2.0) ``` Before change: ``` @benchmark(func(2.0)) = Trial(94.464 ns) @benchmark(func_threaded(2.0)) = Trial(8.228 μs) ``` After change: ``` @benchmark(func(2.0)) = Trial(93.766 ns) @benchmark(func_threaded(2.0)) = Trial(93.765 ns) ```
1 parent 6d23d52 commit 26b7cdc

File tree

1 file changed

+4
-0
lines changed

1 file changed

+4
-0
lines changed

base/threadingconstructs.jl

+4
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,10 @@ macro threads(args...)
9797
throw(ArgumentError("need an expression argument to @threads"))
9898
end
9999
if ex.head === :for
100+
# If we are only running with one thread, just run the for loop directly
101+
if nthreads() == 1
102+
return esc(ex)
103+
end
100104
return _threadsfor(ex.args[1], ex.args[2])
101105
else
102106
throw(ArgumentError("unrecognized argument to @threads"))

0 commit comments

Comments
 (0)