Skip to content

Commit a67924b

Browse files
TortarDatseris
andauthored
Improve performance of sample! function (#765)
* Improve performance of sample! function * use model[id] Co-authored-by: George Datseris <[email protected]> * comment about counter * Update CHANGELOG.md --------- Co-authored-by: George Datseris <[email protected]>
1 parent 788e1f7 commit a67924b

File tree

2 files changed

+11
-7
lines changed

2 files changed

+11
-7
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
# main
2+
- `sample!` is now much faster than before when the size of the sample is big, with a size of 1 million agents the function is now 1000x faster.
23
- A memory bug about offsets calculation has been solved; besides, the `calculate_offsets` function has been sped-up by a significant amount.
34

45
# v5.8

src/simulations/sample.jl

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ function sample!(
2424
weight = nothing;
2525
replace = true,
2626
)
27-
nagents(model) > 0 || return
27+
nagents(model) == 0 && return nothing
2828
org_ids = collect(allids(model))
2929
if weight !== nothing
3030
weights = Weights([get_data(a, weight, identity) for a in values(model.agents)])
@@ -35,16 +35,19 @@ function sample!(
3535
add_newids!(model, org_ids, newids)
3636
end
3737

38-
"Used in sample!"
38+
#Used in sample!
3939
function add_newids!(model, org_ids, newids)
40+
# `counter` counts the number of occurencies for each item, it comes from DataStructure.jl
41+
count_newids = counter(newids)
4042
n = nextid(model)
4143
for id in org_ids
42-
if !in(id, newids)
43-
kill_agent!(model.agents[id], model)
44+
noccurances = count_newids[id]
45+
agent = model[id]
46+
if noccurances == 0
47+
kill_agent!(agent, model)
4448
else
45-
noccurances = count(x -> x == id, newids)
46-
for t in 2:noccurances
47-
newagent = deepcopy(model.agents[id])
49+
for _ in 2:noccurances
50+
newagent = deepcopy(agent)
4851
newagent.id = n
4952
add_agent_pos!(newagent, model)
5053
n += 1

0 commit comments

Comments
 (0)