affinitypool 0.6.0

A Rust library for running blocking jobs on a dedicated thread pool with CPU core affinity
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
use affinitypool::{Builder, Threadpool};
use criterion::{BenchmarkId, Criterion, Throughput, criterion_group, criterion_main};
use std::hint::black_box;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, Instant};
use tokio::runtime::Runtime;

const TASK_COUNTS: &[usize] = &[100, 1000, 10000, 50000];
const WORKER_COUNTS: &[usize] = &[1, 2, 4, 8];

/// A simple CPU-intensive task for benchmarking
fn cpu_task(iterations: usize) -> usize {
	let mut sum: usize = 0;
	for i in 0..iterations {
		sum = sum.wrapping_add(i * 17 + 42);
	}
	sum
}

/// Benchmark basic threadpool operations with different worker counts
fn bench_basic_operations(c: &mut Criterion) {
	let rt = Runtime::new().unwrap();

	let mut group = c.benchmark_group("basic_operations");

	for &workers in WORKER_COUNTS {
		for &task_count in &[100, 1000, 10000] {
			group.throughput(Throughput::Elements(task_count as u64));

			group.bench_with_input(
				BenchmarkId::new(format!("{}_workers", workers), task_count),
				&(workers, task_count),
				|b, &(workers, task_count)| {
					b.iter_custom(|iters| {
						rt.block_on(async move {
							let mut total_duration = Duration::from_nanos(0);

							for _iter in 0..iters {
								let pool = Threadpool::new(workers);
								let start = Instant::now();

								let mut handles = Vec::with_capacity(task_count);
								for _ in 0..task_count {
									handles.push(pool.spawn(|| black_box(cpu_task(100))));
								}

								for handle in handles {
									black_box(handle.await);
								}

								total_duration += start.elapsed();
							}

							total_duration
						})
					});
				},
			);
		}
	}
	group.finish();
}

/// Benchmark high contention scenario - many concurrent tasks with single worker
fn bench_single_worker_contention(c: &mut Criterion) {
	let rt = Runtime::new().unwrap();

	let mut group = c.benchmark_group("single_worker_contention");
	group.measurement_time(Duration::from_secs(10));

	for &task_count in TASK_COUNTS {
		group.throughput(Throughput::Elements(task_count as u64));

		group.bench_with_input(
			BenchmarkId::new("single_worker", task_count),
			&task_count,
			|b, &task_count| {
				b.iter_custom(|iters| {
					rt.block_on(async move {
						let mut total_duration = Duration::from_nanos(0);

						for _iter in 0..iters {
							let pool = Threadpool::new(1);
							let counter = Arc::new(AtomicUsize::new(0));
							let start = Instant::now();

							let mut handles = Vec::with_capacity(task_count);
							for i in 0..task_count {
								let counter_clone = counter.clone();
								handles.push(pool.spawn(move || {
									// Mix of CPU work and atomic operations to simulate real work
									let result = cpu_task(50 + (i % 100));
									counter_clone.fetch_add(result, Ordering::Relaxed);
									result
								}));
							}

							for handle in handles {
								black_box(handle.await);
							}

							black_box(counter.load(Ordering::Relaxed));
							total_duration += start.elapsed();
						}

						total_duration
					})
				});
			},
		);
	}
	group.finish();
}

/// Benchmark optimal contention scenario - many concurrent tasks with 4 workers
fn bench_multi_worker_contention(c: &mut Criterion) {
	let rt = Runtime::new().unwrap();

	let mut group = c.benchmark_group("four_worker_contention");
	group.measurement_time(Duration::from_secs(10));

	for &task_count in TASK_COUNTS {
		group.throughput(Throughput::Elements(task_count as u64));

		group.bench_with_input(
			BenchmarkId::new("four_workers", task_count),
			&task_count,
			|b, &task_count| {
				b.iter_custom(|iters| {
					rt.block_on(async move {
						let mut total_duration = Duration::from_nanos(0);

						for _iter in 0..iters {
							let pool = Threadpool::new(4);
							let counter = Arc::new(AtomicUsize::new(0));
							let start = Instant::now();

							let mut handles = Vec::with_capacity(task_count);
							for i in 0..task_count {
								let counter_clone = counter.clone();
								handles.push(pool.spawn(move || {
									// Mix of CPU work and atomic operations
									let result = cpu_task(50 + (i % 100));
									counter_clone.fetch_add(result, Ordering::Relaxed);
									result
								}));
							}

							for handle in handles {
								black_box(handle.await);
							}

							black_box(counter.load(Ordering::Relaxed));
							total_duration += start.elapsed();
						}

						total_duration
					})
				});
			},
		);
	}
	group.finish();
}

/// Benchmark per-core affinity scenario - many concurrent tasks with thread per core
fn bench_per_core_contention(c: &mut Criterion) {
	let rt = Runtime::new().unwrap();
	let num_cores = num_cpus::get();

	let mut group = c.benchmark_group("per_core_contention");
	group.measurement_time(Duration::from_secs(10));

	for &task_count in TASK_COUNTS {
		group.throughput(Throughput::Elements(task_count as u64));

		group.bench_with_input(
			BenchmarkId::new(format!("{}_cores", num_cores), task_count),
			&task_count,
			|b, &task_count| {
				b.iter_custom(|iters| {
					rt.block_on(async move {
						let mut total_duration = Duration::from_nanos(0);

						for _iter in 0..iters {
							let pool = Builder::new().thread_per_core(true).build();
							let counter = Arc::new(AtomicUsize::new(0));
							let start = Instant::now();

							let mut handles = Vec::with_capacity(task_count);
							for i in 0..task_count {
								let counter_clone = counter.clone();
								handles.push(pool.spawn(move || {
									// CPU-intensive work that benefits from core affinity
									let result = cpu_task(75 + (i % 150));
									counter_clone.fetch_add(result, Ordering::Relaxed);
									result
								}));
							}

							for handle in handles {
								black_box(handle.await);
							}

							black_box(counter.load(Ordering::Relaxed));
							total_duration += start.elapsed();
						}

						total_duration
					})
				});
			},
		);
	}
	group.finish();
}

/// Benchmark throughput comparison across different pool configurations
fn bench_throughput_comparison(c: &mut Criterion) {
	let rt = Runtime::new().unwrap();
	let num_cores = num_cpus::get();

	let mut group = c.benchmark_group("throughput_comparison");
	group.measurement_time(Duration::from_secs(15));

	const THROUGHPUT_TASKS: usize = 20000;
	group.throughput(Throughput::Elements(THROUGHPUT_TASKS as u64));

	// Single worker
	group.bench_function("1_worker", |b| {
		b.iter_custom(|iters| {
			rt.block_on(async move {
				let mut total_duration = Duration::from_nanos(0);

				for _iter in 0..iters {
					let pool = Threadpool::new(1);
					let start = Instant::now();

					let mut handles = Vec::with_capacity(THROUGHPUT_TASKS);
					for i in 0..THROUGHPUT_TASKS {
						handles.push(pool.spawn(move || cpu_task(25 + (i % 50))));
					}

					for handle in handles {
						black_box(handle.await);
					}

					total_duration += start.elapsed();
				}

				total_duration
			})
		});
	});

	// Four workers
	group.bench_function("4_workers", |b| {
		b.iter_custom(|iters| {
			rt.block_on(async move {
				let mut total_duration = Duration::from_nanos(0);

				for _iter in 0..iters {
					let pool = Threadpool::new(4);
					let start = Instant::now();

					let mut handles = Vec::with_capacity(THROUGHPUT_TASKS);
					for i in 0..THROUGHPUT_TASKS {
						handles.push(pool.spawn(move || cpu_task(25 + (i % 50))));
					}

					for handle in handles {
						black_box(handle.await);
					}

					total_duration += start.elapsed();
				}

				total_duration
			})
		});
	});

	// Per-core workers
	group.bench_function(format!("{}_cores_affinity", num_cores).as_str(), |b| {
		b.iter_custom(|iters| {
			rt.block_on(async move {
				let mut total_duration = Duration::from_nanos(0);

				for _iter in 0..iters {
					let pool = Builder::new().thread_per_core(true).build();
					let start = Instant::now();

					let mut handles = Vec::with_capacity(THROUGHPUT_TASKS);
					for i in 0..THROUGHPUT_TASKS {
						handles.push(pool.spawn(move || cpu_task(25 + (i % 50))));
					}

					for handle in handles {
						black_box(handle.await);
					}

					total_duration += start.elapsed();
				}

				total_duration
			})
		});
	});

	// Half cores (for comparison)
	let half_cores = (num_cores / 2).max(1);
	group.bench_function(format!("{}_workers", half_cores).as_str(), |b| {
		b.iter_custom(|iters| {
			rt.block_on(async move {
				let mut total_duration = Duration::from_nanos(0);

				for _iter in 0..iters {
					let pool = Threadpool::new(half_cores);
					let start = Instant::now();

					let mut handles = Vec::with_capacity(THROUGHPUT_TASKS);
					for i in 0..THROUGHPUT_TASKS {
						handles.push(pool.spawn(move || cpu_task(25 + (i % 50))));
					}

					for handle in handles {
						black_box(handle.await);
					}

					total_duration += start.elapsed();
				}

				total_duration
			})
		});
	});

	group.finish();
}

/// Benchmark latency characteristics of different pool configurations
fn bench_task_latency(c: &mut Criterion) {
	let rt = Runtime::new().unwrap();

	let mut group = c.benchmark_group("task_latency");

	// Test latency with different pool configurations
	let configs = vec![
		("single_worker", 1, false),
		("four_workers", 4, false),
		("per_core_affinity", 0, true), // 0 will be ignored when thread_per_core is true
	];

	for (name, workers, per_core) in configs {
		group.bench_function(name, |b| {
			b.iter_custom(|iters| {
				rt.block_on(async move {
					let mut total_duration = Duration::from_nanos(0);

					for _iter in 0..iters {
						let pool = if per_core {
							Builder::new().thread_per_core(true).build()
						} else {
							Threadpool::new(workers)
						};

						// Measure latency of single task execution
						let start = Instant::now();
						let result = pool.spawn(|| cpu_task(100)).await;
						let latency = start.elapsed();
						total_duration += latency;

						black_box(result);
					}

					total_duration
				})
			});
		});
	}

	group.finish();
}

/// Benchmark memory usage patterns and cleanup
fn bench_memory_patterns(c: &mut Criterion) {
	let rt = Runtime::new().unwrap();

	let mut group = c.benchmark_group("memory_patterns");

	// Test rapid pool creation and destruction
	group.bench_function("pool_creation_destruction", |b| {
		b.iter_custom(|iters| {
			rt.block_on(async move {
				let mut total_duration = Duration::from_nanos(0);

				for _iter in 0..iters {
					let start = Instant::now();
					let pool = Builder::new().worker_threads(4).build();

					// Submit a few tasks to actually use the pool
					let mut handles = Vec::new();
					for _ in 0..10 {
						handles.push(pool.spawn(|| cpu_task(10)));
					}

					for handle in handles {
						black_box(handle.await);
					}

					// Pool drops here
					total_duration += start.elapsed();
				}

				total_duration
			})
		});
	});

	// Test task burst patterns
	group.bench_function("task_bursts", |b| {
		b.iter_custom(|iters| {
			rt.block_on(async move {
				let mut total_duration = Duration::from_nanos(0);

				for _iter in 0..iters {
					let pool = Threadpool::new(4);
					let start = Instant::now();

					// Simulate burst of tasks followed by quiet period
					for burst in 0..5 {
						let mut handles = Vec::new();
						for _ in 0..100 {
							handles.push(pool.spawn(move || cpu_task(20 + burst * 5)));
						}

						for handle in handles {
							black_box(handle.await);
						}

						// Small delay between bursts
						tokio::time::sleep(Duration::from_millis(1)).await;
					}

					total_duration += start.elapsed();
				}

				total_duration
			})
		});
	});

	group.finish();
}

criterion_group!(
	benches,
	bench_basic_operations,
	bench_single_worker_contention,
	bench_multi_worker_contention,
	bench_per_core_contention,
	bench_throughput_comparison,
	bench_task_latency,
	bench_memory_patterns
);

criterion_main!(benches);