Skip to content

Commit e4df007

Browse files
Merge pull request #15 from thomvet/grow-cache-on-demand
Enlarging dualcache on demand first time it's called.
2 parents cfcf18e + b34b9dc commit e4df007

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

Project.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
name = "PreallocationTools"
22
uuid = "d236fae5-4411-538c-8e31-a6e3d9e00b46"
33
authors = ["Chris Rackauckas <[email protected]>"]
4-
version = "0.2.0"
4+
version = "0.2.1"
55

66
[deps]
77
Adapt = "79e6a3ab-5dfb-504d-930d-738a2a938a0e"

src/PreallocationTools.jl

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,23 +35,41 @@ Returns the `Dual` or normal cache array stored in `dc` based on the type of `u`
3535
"""
3636
function get_tmp(dc::DiffCache, u::T) where T<:ForwardDiff.Dual
3737
nelem = div(sizeof(T), sizeof(eltype(dc.dual_du)))*length(dc.du)
38+
if nelem > length(dc.dual_du)
39+
enlargedualcache!(dc, nelem)
40+
end
3841
ArrayInterface.restructure(dc.du, reinterpret(T, view(dc.dual_du, 1:nelem)))
3942
end
4043

4144
function get_tmp(dc::DiffCache, u::AbstractArray{T}) where T<:ForwardDiff.Dual
4245
nelem = div(sizeof(T), sizeof(eltype(dc.dual_du)))*length(dc.du)
46+
if nelem > length(dc.dual_du)
47+
enlargedualcache!(dc, nelem)
48+
end
4349
ArrayInterface.restructure(dc.du, reinterpret(T, view(dc.dual_du, 1:nelem)))
4450
end
4551

4652
function get_tmp(dc::DiffCache, u::LabelledArrays.LArray{T,N,D,Syms}) where {T,N,D,Syms}
4753
nelem = div(sizeof(T), sizeof(eltype(dc.dual_du)))*length(dc.du)
54+
if nelem > length(dc.dual_du)
55+
enlargedualcache!(dc, nelem)
56+
end
4857
_x = ArrayInterface.restructure(dc.du, reinterpret(T, view(dc.dual_du, 1:nelem)))
4958
LabelledArrays.LArray{T,N,D,Syms}(_x)
5059
end
5160

5261
get_tmp(dc::DiffCache, u::Number) = dc.du
5362
get_tmp(dc::DiffCache, u::AbstractArray) = dc.du
5463

64+
function enlargedualcache!(dc, nelem) #warning comes only once per dualcache.
65+
chunksize = div(nelem, length(dc.du)) - 1
66+
@warn "The supplied dualcache was too small and was enlarged. This incurrs allocations
67+
on the first call to get_tmp. If few calls to get_tmp occur and optimal performance is essential,
68+
consider changing 'N'/chunk size of this dualcache to $chunksize."
69+
resize!(dc.dual_du, nelem)
70+
end
71+
72+
5573
"""
5674
b = LazyBufferCache(f=identity)
5775

0 commit comments

Comments
 (0)