Skip to content

@ccallable allocates for its arguments #51894

@vchuravy

Description

@vchuravy

From https://discourse.julialang.org/t/gc-occurs-at-the-worst-time-in-tight-loop-garbage-collection/104934/82?u=vchuravy

Base.@ccallable function julia_set_dB_gain(dB_gain::Cdouble)::Cvoid 
    return nothing
end

f(x) = ccall("extern julia_set_dB_gain", llvmcall, Cvoid, (Cdouble,), x)


using BenchmarkTools

julia> @benchmark f(1.0)
BenchmarkTools.Trial: 10000 samples with 998 evaluations.
 Range (min … max):  16.092 ns … 230.391 ns  ┊ GC (min … max): 0.00% … 83.13%
 Time  (median):     17.305 ns               ┊ GC (median):    0.00%
 Time  (mean ± σ):   18.390 ns ±   6.985 ns  ┊ GC (mean ± σ):  0.48% ±  2.21%

  ▂     ▆█▄▃▁▅                           ▁▃▂▁▁       ▁         ▂
  █▅▁▄▅▆███████▅▅▇▆▃▃▄▁▁▃▃▄▄▅▄▄▅▆█▇▇▆▅▅▄▄██████▇▆▅▄▅███▇▇▆▅▄▁▃ █
  16.1 ns       Histogram: log(frequency) by time      26.1 ns <

 Memory estimate: 16 bytes, allocs estimate: 1.

Where as @cfunction avoids the allocation:

julia> Base.@cfunction function julia_set_dB_gain(dB_gain::Cdouble)::Cvoid 
           return nothing
       end Cvoid (Cdouble,)
Ptr{Nothing} @0x00007fbbd0a4cff0

julia> f(x) = ccall(Ptr{Cvoid}(0x00007fbbd0a4cff0), Cvoid, (Cdouble,), x)
f (generic function with 1 method)

julia> @benchmark f(1.0)
BenchmarkTools.Trial: 10000 samples with 1000 evaluations.
 Range (min … max):  5.999 ns … 41.309 ns  ┊ GC (min … max): 0.00% … 0.00%
 Time  (median):     6.000 ns              ┊ GC (median):    0.00%
 Time  (mean ± σ):   6.049 ns ±  0.491 ns  ┊ GC (mean ± σ):  0.00% ± 0.00%

  █ ▂                                                      ▂ ▁
  █▇█▅▄▄▄▃▃▁▃▃▃▁▁▄▁▁▃▁▁▃▃▃▁▁▁▄▁▃▄▁▁▃▁▁▃▄▁▄▅▆▁▄▁▁▄▁▄▄▃▁▄▃▁▁▃█ █
  6 ns         Histogram: log(frequency) by time     7.11 ns <

 Memory estimate: 0 bytes, allocs estimate: 0.

@vtjnash comment was: that is probably what @ccallable is supposed to do too

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions