Large allocations with MTK event

klinders
Wed, 05 Nov 2025 12:14:04 +0000
Performance

Dear all,

Recently, you helped me get events working in MTK. Thank you for all the help!

Continuing on the topic, I ran into a performance issue with events. I have the following code to measure the time and allocations for a system with and without events.

using ModelingToolkit
using ModelingToolkit: t_nounits as t, D_nounits as D

function affect!(mod,obs,ctx,int)
    ModelingToolkit.terminate!(int)

    return (;)
end

function FOL_event(;name)
    @parameters begin
        τ = 3.0 # parameters
    end
    @variables begin
        x(t) = 0.0 # dependent variables
    end
    eq=[
        D(x) ~ (1 - x) / τ
    ]

    events = [x ~ 0.6]=>(affect!,(;))

    return System(eq, t; name=name, continuous_events=events)
end

function FOL(;name)
    @parameters begin
        τ = 3.0 # parameters
    end
    @variables begin
        x(t) = 0.0 # dependent variables
    end
    eq=[
        D(x) ~ (1 - x) / τ
    ]

    return System(eq, t; name=name)
end

using OrdinaryDiffEq
@mtkbuild fol = FOL()
@mtkbuild fol_event = FOL_event()

print("Starting problems\n")
print("No event:")
@time prob = ODEProblem(fol, [], (0.0, 10.0), dense=true,save_everystep=false)
print("With event:")
@time prob_event = ODEProblem(fol_event, [], (0.0, 10.0), dense=true, save_everystep=false)

print("Solving problems\n")
print("No event:")
@time sol = solve(prob,Tsit5())
print("With event:")
@time sol_event = solve(prob_event, Tsit5())

If I run the code for the second time to skip compilation, I get the following output:

Starting problems
No event:  0.009388 seconds (39.02 k allocations: 2.201 MiB)
With event:  0.007077 seconds (36.27 k allocations: 1.683 MiB)
Solving problems
No event:  0.000044 seconds (88 allocations: 6.578 KiB)
With event:  0.119570 seconds (144.21 k allocations: 8.894 MiB, 99.95% compilation time: 100% of which was recompilation)

With the events, the solving takes much longer and uses much more memory.

The topic seems similar to Significant allocations with Callbacks (Tsit5) , but since those fixes were merged a long time ago, I decided to open a new issue.

Im running: Julia 1.10.10, MTK 10.26.1, and OrdinaryDiffEq 6.103.0

I look forward to hearing your ideas.

Kind regards,

Koen Linders

2 posts - 2 participants