Weird @btime results with `sin`

I was profiling timing differences between using sin, sind, and I noticed some interesting results.

julia> using BenchmarkTools

julia> sin(10);

julia> sind(10);

julia> const ° = π/180;

julia> x = 1.234;

julia> @btime sin($x)
  6.289 ns (0 allocations: 0 bytes)
0.9438182093746337

julia> @btime sind($x)
  10.923 ns (0 allocations: 0 bytes)
0.02153569796186157

julia> @btime sin($x * $°)
  4.280 ns (0 allocations: 0 bytes)
0.021535697961861566

Why is the last one faster than the first one? It’s the same function. From what I understand, it should be slower if anything, since there’s an additional multiplication involved.

4 Likes

Functions like sin are usually implemented by a “range reduction” to map the input to a smaller region, and then some kind of series expansion to approximate the function on that small range. My guess is that by rescaling the input by pi/180 you are ending up with something small enough to skip the range reduction step which then speeds up the function evaluation.

This came up recently in another post on here, which is where I learned about this phenomenon.

5 Likes