Skip to content

Commit

Permalink
Fast-track @threads when nthreads() == 1
Browse files Browse the repository at this point in the history
This avoids overhead when threading is disabled, Example benchmark:

```
using BenchmarkTools, Base.Threads

function func(val)
    sum = 0*(1 .^ val)
    for idx in 1:100
        sum += idx.^val
    end
    return sum
end

function func_threaded(val)
    sum = 0*(1 .^ val)
    @threads for idx in 1:100
        sum += idx.^val
    end
    return sum
end

function func_threaded_ref(val)
    sum = Ref(0*(1 .^ val))
    @threads for idx in 1:100
        sum[] += idx.^val
    end
    return sum[]
end

@show @benchmark func(2.0)
@show @benchmark func_threaded(2.0)
@show @benchmark func_threaded_ref(2.0)
```

Before change:
```
@benchmark(func(2.0)) = Trial(94.020 ns)
@benchmark(func_threaded(2.0)) = Trial(5.623 μs)
@benchmark(func_threaded_ref(2.0)) = Trial(3.913 μs)
```

After change:
```
@benchmark(func(2.0)) = Trial(93.124 ns)
@benchmark(func_threaded(2.0)) = Trial(2.175 μs)
@benchmark(func_threaded_ref(2.0)) = Trial(554.128 ns)
```
  • Loading branch information
staticfloat committed Jun 19, 2019
1 parent 48bf04c commit 78eb422
Showing 1 changed file with 2 additions and 2 deletions.
4 changes: 2 additions & 2 deletions base/threadingconstructs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,8 @@ function _threadsfor(iter,lbody)
end
end
# Hack to make nested threaded loops kinda work
if threadid() != 1 || in_threaded_loop[]
# We are in a nested threaded loop
if nthreads() == 1 || threadid() != 1 || in_threaded_loop[]
# We are in a nested threaded loop, or running single-threaded
Base.invokelatest(threadsfor_fun, true)
else
in_threaded_loop[] = true
Expand Down

0 comments on commit 78eb422

Please sign in to comment.