1//! Benchmark spawning a task onto the basic and threaded Tokio executors.
2//! This essentially measure the time to enqueue a task in the local and remote
3//! case.
4
5use criterion::{black_box, criterion_group, criterion_main, Criterion};
6
7async fn work() -> usize {
8 let val = 1 + 1;
9 tokio::task::yield_now().await;
10 black_box(val)
11}
12
13fn basic_scheduler_spawn(c: &mut Criterion) {
14 let runtime = tokio::runtime::Builder::new_current_thread()
15 .build()
16 .unwrap();
17
18 c.bench_function("basic_scheduler_spawn", |b| {
19 b.iter(|| {
20 runtime.block_on(async {
21 let h = tokio::spawn(work());
22 assert_eq!(h.await.unwrap(), 2);
23 });
24 })
25 });
26}
27
28fn basic_scheduler_spawn10(c: &mut Criterion) {
29 let runtime = tokio::runtime::Builder::new_current_thread()
30 .build()
31 .unwrap();
32
33 c.bench_function("basic_scheduler_spawn10", |b| {
34 b.iter(|| {
35 runtime.block_on(async {
36 let mut handles = Vec::with_capacity(10);
37 for _ in 0..10 {
38 handles.push(tokio::spawn(work()));
39 }
40 for handle in handles {
41 assert_eq!(handle.await.unwrap(), 2);
42 }
43 });
44 })
45 });
46}
47
48fn threaded_scheduler_spawn(c: &mut Criterion) {
49 let runtime = tokio::runtime::Builder::new_multi_thread()
50 .worker_threads(1)
51 .build()
52 .unwrap();
53 c.bench_function("threaded_scheduler_spawn", |b| {
54 b.iter(|| {
55 runtime.block_on(async {
56 let h = tokio::spawn(work());
57 assert_eq!(h.await.unwrap(), 2);
58 });
59 })
60 });
61}
62
63fn threaded_scheduler_spawn10(c: &mut Criterion) {
64 let runtime = tokio::runtime::Builder::new_multi_thread()
65 .worker_threads(1)
66 .build()
67 .unwrap();
68 c.bench_function("threaded_scheduler_spawn10", |b| {
69 b.iter(|| {
70 runtime.block_on(async {
71 let mut handles = Vec::with_capacity(10);
72 for _ in 0..10 {
73 handles.push(tokio::spawn(work()));
74 }
75 for handle in handles {
76 assert_eq!(handle.await.unwrap(), 2);
77 }
78 });
79 })
80 });
81}
82
83criterion_group!(
84 spawn,
85 basic_scheduler_spawn,
86 basic_scheduler_spawn10,
87 threaded_scheduler_spawn,
88 threaded_scheduler_spawn10,
89);
90
91criterion_main!(spawn);
92