atagen

matrix-rust-sdk

public
Star0
Watch0
ssh://brewery@pls.lobotomise.me:33/atagen/matrix-rust-sdk.git
benchmarks/benches/linked_chunk.rsRust263 lines9.5 KB
1
use std::{sync::Arc, time::Duration};
2
3
use criterion::{BatchSize, BenchmarkId, Criterion, Throughput, criterion_group, criterion_main};
4
use matrix_sdk::{
5
    SqliteEventCacheStore,
6
    linked_chunk::{LinkedChunk, LinkedChunkId, Update, lazy_loader},
7
};
8
use matrix_sdk_base::event_cache::{
9
    Event, Gap,
10
    store::{DEFAULT_CHUNK_CAPACITY, DynEventCacheStore, IntoEventCacheStore, MemoryStore},
11
};
12
use matrix_sdk_test::{ALICE, event_factory::EventFactory};
13
use ruma::room_id;
14
use tempfile::tempdir;
15
use tokio::runtime::Builder;
16
17
#[derive(Clone, Debug)]
18
enum Operation {
19
    PushItemsBack(Vec<Event>),
20
    PushGapBack(Gap),
21
}
22
23
#[cfg(not(feature = "codspeed"))]
24
const NUMBER_OF_EVENTS: &[u64] = &[10, 100, 1000, 10_000, 100_000];
25
#[cfg(feature = "codspeed")]
26
const NUMBER_OF_EVENTS: &[u64] = &[10, 100, 1000];
27
28
fn writing(c: &mut Criterion) {
29
    // Create a new asynchronous runtime.
30
    let runtime = Builder::new_multi_thread()
31
        .enable_time()
32
        .enable_io()
33
        .build()
34
        .expect("Failed to create an asynchronous runtime");
35
36
    let room_id = room_id!("!fabricandofitfaber:bar.baz");
37
    let linked_chunk_id = LinkedChunkId::Room(room_id);
38
    let event_factory = EventFactory::new().room(room_id).sender(&ALICE);
39
40
    let mut group = c.benchmark_group("Linked chunk writing");
41
    group.sample_size(10).measurement_time(Duration::from_secs(30));
42
43
    for &number_of_events in NUMBER_OF_EVENTS {
44
        let sqlite_temp_dir = tempdir().unwrap();
45
46
        // Declare new stores for this set of events.
47
        let stores: [(&str, Option<Arc<DynEventCacheStore>>); 3] = [
48
            ("none", None),
49
            ("memory store", Some(MemoryStore::default().into_event_cache_store())),
50
            (
51
                "sqlite store",
52
                runtime.block_on(async {
53
                    Some(
54
                        SqliteEventCacheStore::open(sqlite_temp_dir.path().join("bench"), None)
55
                            .await
56
                            .unwrap()
57
                            .into_event_cache_store(),
58
                    )
59
                }),
60
            ),
61
        ];
62
63
        for (store_name, store) in stores {
64
            // Create the operations we want to bench.
65
            let mut operations = Vec::new();
66
67
            {
68
                let mut events = (0..number_of_events)
69
                    .map(|nth| event_factory.text_msg(format!("foo {nth}")).into_event())
70
                    .peekable();
71
72
                let mut gap_nth = 0;
73
74
                while events.peek().is_some() {
75
                    {
76
                        let events_to_push_back = events.by_ref().take(80).collect::<Vec<_>>();
77
78
                        if events_to_push_back.is_empty() {
79
                            break;
80
                        }
81
82
                        operations.push(Operation::PushItemsBack(events_to_push_back));
83
                    }
84
85
                    {
86
                        operations
87
                            .push(Operation::PushGapBack(Gap { token: format!("gap{gap_nth}") }));
88
                        gap_nth += 1;
89
                    }
90
                }
91
            }
92
93
            // Define the throughput.
94
            group.throughput(Throughput::Elements(number_of_events));
95
96
            // Get a bencher.
97
            group.bench_with_input(
98
                BenchmarkId::new(format!("Linked chunk writing [{store_name}]"), number_of_events),
99
                &operations,
100
                |bencher, operations| {
101
                    // Bench the routine.
102
                    bencher.to_async(&runtime).iter_batched(
103
                        || operations.clone(),
104
                        |operations| async {
105
                            // The routine to bench!
106
107
                            let mut linked_chunk = LinkedChunk::<DEFAULT_CHUNK_CAPACITY, Event, Gap>::new_with_update_history();
108
109
                            for operation in operations {
110
                                match operation {
111
                                    Operation::PushItemsBack(events) => linked_chunk.push_items_back(events),
112
                                    Operation::PushGapBack(gap) => linked_chunk.push_gap_back(gap),
113
                                }
114
                            }
115
116
                            if let Some(store) = &store {
117
                                let updates = linked_chunk.updates().unwrap().take();
118
                                store.handle_linked_chunk_updates(linked_chunk_id, updates).await.unwrap();
119
                                // Empty the store.
120
                                store.handle_linked_chunk_updates(linked_chunk_id, vec![Update::Clear]).await.unwrap();
121
                            }
122
123
                        },
124
                        BatchSize::SmallInput
125
                    )
126
                },
127
            );
128
129
            {
130
                let _guard = runtime.enter();
131
                drop(store);
132
            }
133
        }
134
    }
135
136
    group.finish()
137
}
138
139
fn reading(c: &mut Criterion) {
140
    // Create a new asynchronous runtime.
141
    let runtime = Builder::new_multi_thread()
142
        .enable_time()
143
        .enable_io()
144
        .build()
145
        .expect("Failed to create an asynchronous runtime");
146
147
    let room_id = room_id!("!fabricandofitfaber:bar.baz");
148
    let linked_chunk_id = LinkedChunkId::Room(room_id);
149
    let event_factory = EventFactory::new().room(room_id).sender(&ALICE);
150
151
    let mut group = c.benchmark_group("Linked chunk reading");
152
    group.sample_size(10);
153
154
    for &num_events in NUMBER_OF_EVENTS {
155
        let sqlite_temp_dir = tempdir().unwrap();
156
157
        // Declare new stores for this set of events.
158
        let stores: [(&str, Arc<DynEventCacheStore>); 2] = [
159
            ("memory store", MemoryStore::default().into_event_cache_store()),
160
            (
161
                "sqlite store",
162
                runtime.block_on(async {
163
                    SqliteEventCacheStore::open(sqlite_temp_dir.path().join("bench"), None)
164
                        .await
165
                        .unwrap()
166
                        .into_event_cache_store()
167
                }),
168
            ),
169
        ];
170
171
        for (store_name, store) in stores {
172
            // Store some events and gap chunks in the store.
173
            {
174
                let mut events = (0..num_events)
175
                    .map(|nth| event_factory.text_msg(format!("foo {nth}")).into_event())
176
                    .peekable();
177
178
                let mut lc =
179
                    LinkedChunk::<DEFAULT_CHUNK_CAPACITY, Event, Gap>::new_with_update_history();
180
                let mut num_gaps = 0;
181
182
                while events.peek().is_some() {
183
                    let events_chunk = events.by_ref().take(80).collect::<Vec<_>>();
184
185
                    if events_chunk.is_empty() {
186
                        break;
187
                    }
188
189
                    lc.push_items_back(events_chunk);
190
                    lc.push_gap_back(Gap { token: format!("gap{num_gaps}") });
191
192
                    num_gaps += 1;
193
                }
194
195
                // Now persist the updates to recreate this full linked chunk.
196
                let updates = lc.updates().unwrap().take();
197
                runtime
198
                    .block_on(store.handle_linked_chunk_updates(linked_chunk_id, updates))
199
                    .unwrap();
200
            }
201
202
            // Define the throughput.
203
            group.throughput(Throughput::Elements(num_events));
204
205
            // Bench the lazy loader.
206
            group.bench_function(
207
                BenchmarkId::new(format!("Linked chunk lazy loader[{store_name}]"), num_events),
208
                |bencher| {
209
                    // Bench the routine.
210
                    bencher.to_async(&runtime).iter(|| async {
211
                        // Load the last chunk first,
212
                        let (last_chunk, chunk_id_gen) =
213
                            store.load_last_chunk(linked_chunk_id).await.unwrap();
214
215
                        let mut lc =
216
                            lazy_loader::from_last_chunk::<128, _, _>(last_chunk, chunk_id_gen)
217
                                .expect("no error when reconstructing the linked chunk")
218
                                .expect("there is a linked chunk in the store");
219
220
                        // Then load until the start of the linked chunk.
221
                        let mut cur_chunk_id = lc.chunks().next().unwrap().identifier();
222
                        while let Some(prev) =
223
                            store.load_previous_chunk(linked_chunk_id, cur_chunk_id).await.unwrap()
224
                        {
225
                            cur_chunk_id = prev.identifier;
226
                            lazy_loader::insert_new_first_chunk(&mut lc, prev)
227
                                .expect("no error when linking the previous lazy-loaded chunk");
228
                        }
229
                    })
230
                },
231
            );
232
233
            // Bench the metadata loader.
234
            group.bench_function(
235
                BenchmarkId::new(format!("Linked chunk metadata loader[{store_name}]"), num_events),
236
                |bencher| {
237
                    // Bench the routine.
238
                    bencher.to_async(&runtime).iter(|| async {
239
                        let _metadata = store
240
                            .load_all_chunks_metadata(linked_chunk_id)
241
                            .await
242
                            .expect("metadata must load");
243
                    })
244
                },
245
            );
246
247
            {
248
                let _guard = runtime.enter();
249
                drop(store);
250
            }
251
        }
252
    }
253
254
    group.finish()
255
}
256
257
criterion_group! {
258
    name = event_cache;
259
    config = Criterion::default();
260
    targets = writing, reading,
261
}
262
263
criterion_main!(event_cache);