clockworker 0.2.2

A single-threaded async executor with EEVDF-based fair scheduling and pluggable task schedulers
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
//! Overhead benchmarks for Clockworker
//!
//! Run with: cargo bench --bench overhead
//!
//! Benchmarks:
//! - 1A: Spawn throughput (minimal work tasks)
//! - 1B: Yield/poll overhead (tasks that yield K times)
//! - 1C: IO reactor integration (timer-based tasks)

use clockworker::ExecutorBuilder;
use futures::future;
use std::io::Write;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::task::LocalSet;

use crate::utils::{Step, Work};

#[allow(dead_code)]
mod utils;

// ============================================================================
// Configuration
// ============================================================================

const WARMUP_ITERS: usize = 3;
const BENCH_ITERS: usize = 10;

// 1A: Spawn throughput
const SPAWN_TASK_COUNTS: &[usize] = &[1_000, 10_000, 100_000];

// 1B: Yield overhead
const YIELD_TASK_COUNT: usize = 1_000;
const YIELDS_PER_TASK: [usize; 3] = [10, 100, 1_000];

// 1C: IO reactor
const IO_TASK_COUNT: usize = 100;
const SLEEPS_PER_TASK: usize = 10;
const SLEEP_DURATION: Duration = Duration::from_micros(500);

async fn drive<F>(
    spawn: impl Fn(F) -> utils::Handle<()>,
    n: usize,
    factory: impl Fn() -> F,
) -> Duration
where
    F: std::future::Future<Output = ()> + 'static,
{
    let start = Instant::now();
    let mut handles = Vec::with_capacity(n);
    for _ in 0..n {
        let fut = factory();
        handles.push(spawn(fut));
    }
    for h in handles {
        let _ = h.await;
    }
    start.elapsed()
}

fn run_1a() -> Vec<utils::Metrics> {
    let mut results = Vec::new();

    for &n in SPAWN_TASK_COUNTS {
        println!("\n  [] Spawn throughput: n={}", n);
        // first run tokio and then clockworker
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap();
        let factory = || async move {
            let fut = Work::new(vec![]);
            fut.run().await
        };

        let mut tokio_result = utils::Metrics::new();
        let mut cw_result = utils::Metrics::new();

        // Warmup
        println!("Warming up Tokio: ");
        for _ in 0..WARMUP_ITERS {
            rt.block_on(async move {
                let local = LocalSet::new();
                let spawn = |fut| {
                    let handle = local.spawn_local(fut);
                    utils::Handle::Tokio(handle)
                };
                local.run_until(drive(spawn, n, factory)).await;
            });
        }
        // Bench
        print!("Running Tokio: ");
        for _ in 0..BENCH_ITERS {
            let dur = rt.block_on(async move {
                let local = LocalSet::new();
                let spawn = |fut| {
                    let handle = local.spawn_local(fut);
                    utils::Handle::Tokio(handle)
                };
                local.run_until(drive(spawn, n, factory)).await
            });
            tokio_result.record(dur, &["spawn"]);
            print!(".");
            std::io::stdout().flush().unwrap();
        }
        println!();
        // now run clockworker
        let executor = ExecutorBuilder::new().with_queue(0u8, 1).build().unwrap();
        let spawn = |fut| {
            let handle = executor.queue(0).unwrap().spawn(fut);
            utils::Handle::Clockworker(handle)
        };
        println!("warming up clockworker");
        std::io::stdout().flush().unwrap();
        for _ in 0..WARMUP_ITERS {
            let executor = executor.clone();
            rt.block_on(async move {
                let local = LocalSet::new();
                local
                    .run_until(executor.run_until(drive(spawn, n, factory)))
                    .await;
            })
        }
        print!("Running Clockworker (FIFO): ");
        std::io::stdout().flush().unwrap();
        for _ in 0..BENCH_ITERS {
            let executor = executor.clone();
            let dur = rt.block_on(async move {
                let local = LocalSet::new();
                local
                    .run_until(executor.run_until(drive(spawn, n, factory)))
                    .await
            });
            cw_result.record(dur, &["spawn"]);
            print!(".");
            std::io::stdout().flush().unwrap();
        }
        println!();

        // Print comparison
        let cw_tput = n as f64 / cw_result.mean("spawn").as_secs_f64();
        let tokio_tput = n as f64 / tokio_result.mean("spawn").as_secs_f64();
        let overhead = (cw_result.mean("spawn").as_secs_f64()
            / tokio_result.mean("spawn").as_secs_f64()
            - 1.0)
            * 100.0;

        println!(
            "    Clockworker: {:.2} tasks/sec (mean: {:?}, stddev: {:?})",
            cw_tput,
            cw_result.mean("spawn"),
            cw_result.stddev("spawn")
        );
        println!(
            "    Tokio:       {:.2} tasks/sec (mean: {:?}, stddev: {:?})",
            tokio_tput,
            tokio_result.mean("spawn"),
            tokio_result.stddev("spawn")
        );
        println!("    Overhead:    {:.1}%", overhead);

        results.push(cw_result);
        results.push(tokio_result);
    }

    results
}

// ============================================================================
// Benchmark 1B: Yield/Poll Overhead
// ============================================================================

fn run_1b() -> Vec<utils::Metrics> {
    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .unwrap();

    let mut results = Vec::new();
    let n = YIELD_TASK_COUNT;

    for k in YIELDS_PER_TASK {
        let total_polls = n * (k + 1); // +1 for final Ready poll
        println!(
            "\n  [1B] Yield overhead: n={}, k={} ({} total polls)",
            n, k, total_polls
        );
        let factory = move || async move {
            let steps = (0..k).map(|_| Step::Yield).collect::<Vec<_>>();
            let fut = Work::new(steps);
            fut.run().await
        };

        // Clockworker with FIFO (lightweight scheduler)
        let mut cw_fifo = utils::Metrics::new();
        let executor = ExecutorBuilder::new().with_queue(0u8, 1).build().unwrap();
        let spawn = |fut| {
            let handle = executor.queue(0).unwrap().spawn(fut);
            utils::Handle::Clockworker(handle)
        };
        println!("Warming up Clockworker (FIFO): ");
        std::io::stdout().flush().unwrap();
        for _ in 0..WARMUP_ITERS {
            let executor = executor.clone();
            rt.block_on(async move {
                let local = LocalSet::new();
                local
                    .run_until(executor.run_until(drive(spawn, n, factory)))
                    .await;
            })
        }
        print!("Running Clockworker (FIFO): ");
        std::io::stdout().flush().unwrap();
        for _ in 0..BENCH_ITERS {
            let executor = executor.clone();
            let dur = rt.block_on(async move {
                let local = LocalSet::new();
                local
                    .run_until(executor.run_until(drive(spawn, n, factory)))
                    .await
            });
            cw_fifo.record(dur, &["yield"]);
            print!(".");
            std::io::stdout().flush().unwrap();
        }
        println!();

        // Tokio baseline
        let mut tokio_result = utils::Metrics::new();
        println!("Warming up Tokio: ");
        std::io::stdout().flush().unwrap();
        for _ in 0..WARMUP_ITERS {
            rt.block_on(async move {
                let local = LocalSet::new();
                let spawn = |fut| {
                    let handle = local.spawn_local(fut);
                    utils::Handle::Tokio(handle)
                };
                local.run_until(drive(spawn, n, factory)).await;
            })
        }
        print!("Running Tokio: ");
        std::io::stdout().flush().unwrap();
        for _ in 0..BENCH_ITERS {
            let dur = rt.block_on(async move {
                let local = LocalSet::new();
                let spawn = |fut| {
                    let handle = local.spawn_local(fut);
                    utils::Handle::Tokio(handle)
                };
                local.run_until(drive(spawn, n, factory)).await
            });
            tokio_result.record(dur, &["yield"]);
            print!(".");
            std::io::stdout().flush().unwrap();
        }
        println!();

        // Print comparison
        let tokio_polls_per_sec = total_polls as f64 / tokio_result.mean("yield").as_secs_f64();
        let fifo_polls_per_sec = total_polls as f64 / cw_fifo.mean("yield").as_secs_f64();
        let fifo_overhead = (cw_fifo.mean("yield").as_nanos() as f64
            / tokio_result.mean("yield").as_nanos() as f64
            - 1.0)
            * 100.0;

        println!(
            "    Tokio:            {:.2e} polls/sec (mean: {:?})",
            tokio_polls_per_sec,
            tokio_result.mean("yield")
        );
        println!(
            "    Clockworker/FIFO: {:.2e} polls/sec (mean: {:?}) [overhead: {:.1}%]",
            fifo_polls_per_sec,
            cw_fifo.mean("yield"),
            fifo_overhead
        );

        results.push(cw_fifo);
        results.push(tokio_result);
    }

    results
}

// ============================================================================
// Benchmark 1C: IO Reactor Integration
// ============================================================================

/// Clockworker: tasks that sleep (exercises reactor integration)
async fn bench_1c_clockworker(
    n: usize,
    sleeps: usize,
    sleep_dur: Duration,
) -> (Duration, Vec<Duration>) {
    let executor = ExecutorBuilder::new().with_queue(0u8, 1).build().unwrap();

    let queue = executor.queue(0).unwrap();

    // Collect actual sleep durations to measure accuracy
    let sleep_accuracies: Arc<std::sync::Mutex<Vec<Duration>>> =
        Arc::new(std::sync::Mutex::new(Vec::new()));

    let start = Instant::now();

    let mut handles = Vec::with_capacity(n);
    for _ in 0..n {
        let accuracies = sleep_accuracies.clone();
        let dur = sleep_dur;
        handles.push(queue.spawn(async move {
            for _ in 0..sleeps {
                let before = Instant::now();
                tokio::time::sleep(dur).await;
                let actual = before.elapsed();
                accuracies.lock().unwrap().push(actual);
            }
        }));
    }

    // Run executor until all handles complete
    let executor_clone = executor.clone();
    executor_clone
        .run_until(async {
            future::join_all(handles).await;
        })
        .await;

    let elapsed = start.elapsed();

    let accuracies = Arc::try_unwrap(sleep_accuracies)
        .unwrap()
        .into_inner()
        .unwrap();
    (elapsed, accuracies)
}

/// Tokio baseline: tasks that sleep
async fn bench_1c_tokio(n: usize, sleeps: usize, sleep_dur: Duration) -> (Duration, Vec<Duration>) {
    let sleep_accuracies: Arc<std::sync::Mutex<Vec<Duration>>> =
        Arc::new(std::sync::Mutex::new(Vec::new()));

    let start = Instant::now();

    let mut handles = Vec::with_capacity(n);
    for _ in 0..n {
        let accuracies = sleep_accuracies.clone();
        let dur = sleep_dur;
        handles.push(tokio::task::spawn_local(async move {
            for _ in 0..sleeps {
                let before = Instant::now();
                tokio::time::sleep(dur).await;
                let actual = before.elapsed();
                accuracies.lock().unwrap().push(actual);
            }
        }));
    }

    for h in handles {
        let _ = h.await;
    }

    let elapsed = start.elapsed();

    let accuracies = Arc::try_unwrap(sleep_accuracies)
        .unwrap()
        .into_inner()
        .unwrap();
    (elapsed, accuracies)
}

fn analyze_sleep_accuracy(
    accuracies: &[Duration],
    expected: Duration,
) -> (Duration, Duration, f64) {
    let mean: Duration = accuracies.iter().sum::<Duration>() / accuracies.len() as u32;
    let max = *accuracies.iter().max().unwrap();
    let overslept_ratio = mean.as_nanos() as f64 / expected.as_nanos() as f64;
    (mean, max, overslept_ratio)
}

fn run_1c() -> Vec<utils::Metrics> {
    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .unwrap();

    let mut results = Vec::new();

    println!(
        "\n  [1C] IO reactor integration: n={}, sleeps={}, sleep_dur={:?}",
        IO_TASK_COUNT, SLEEPS_PER_TASK, SLEEP_DURATION
    );

    let expected_total = SLEEP_DURATION * (SLEEPS_PER_TASK as u32);
    println!(
        "    Expected minimum time: {:?} (if fully parallel)",
        expected_total
    );

    // Clockworker
    let mut cw_result = utils::Metrics::new();
    let mut cw_accuracies = Vec::new();

    for _ in 0..WARMUP_ITERS {
        let local = LocalSet::new();
        rt.block_on(local.run_until(bench_1c_clockworker(
            IO_TASK_COUNT,
            SLEEPS_PER_TASK,
            SLEEP_DURATION,
        )));
    }

    for _ in 0..BENCH_ITERS {
        let local = LocalSet::new();
        let (dur, accuracies) = rt.block_on(local.run_until(bench_1c_clockworker(
            IO_TASK_COUNT,
            SLEEPS_PER_TASK,
            SLEEP_DURATION,
        )));
        cw_result.record(dur, &["sleep"]);
        cw_accuracies.extend(accuracies);
        print!(".");
        std::io::stdout().flush().unwrap();
    }
    println!();

    // Tokio baseline
    let mut tokio_result = utils::Metrics::new();
    let mut tokio_accuracies = Vec::new();

    for _ in 0..WARMUP_ITERS {
        let local = LocalSet::new();
        rt.block_on(local.run_until(bench_1c_tokio(
            IO_TASK_COUNT,
            SLEEPS_PER_TASK,
            SLEEP_DURATION,
        )));
    }

    for _ in 0..BENCH_ITERS {
        let local = LocalSet::new();
        let (dur, accuracies) = rt.block_on(local.run_until(bench_1c_tokio(
            IO_TASK_COUNT,
            SLEEPS_PER_TASK,
            SLEEP_DURATION,
        )));
        tokio_result.record(dur, &["sleep"]);
        tokio_accuracies.extend(accuracies);
        print!(".");
        std::io::stdout().flush().unwrap();
    }
    println!();

    // Analyze
    let (cw_mean_sleep, cw_max_sleep, cw_ratio) =
        analyze_sleep_accuracy(&cw_accuracies, SLEEP_DURATION);
    let (tokio_mean_sleep, tokio_max_sleep, tokio_ratio) =
        analyze_sleep_accuracy(&tokio_accuracies, SLEEP_DURATION);

    println!("    Tokio:");
    println!("      Total time: {:?} (mean)", tokio_result.mean("sleep"));
    println!(
        "      Sleep accuracy: mean={:?} max={:?} ratio={:.2}x",
        tokio_mean_sleep, tokio_max_sleep, tokio_ratio
    );

    println!("    Clockworker:");
    println!("      Total time: {:?} (mean)", cw_result.mean("sleep"));
    println!(
        "      Sleep accuracy: mean={:?} max={:?} ratio={:.2}x",
        cw_mean_sleep, cw_max_sleep, cw_ratio
    );

    let overhead = (cw_result.mean("sleep").as_nanos() as f64
        / tokio_result.mean("sleep").as_nanos() as f64
        - 1.0)
        * 100.0;
    println!("    Overhead: {:.1}%", overhead);

    if cw_ratio > tokio_ratio * 1.5 {
        println!(
            "    ⚠️  WARNING: Clockworker sleeps are {:.1}x longer than Tokio's - possible reactor starvation",
            cw_ratio / tokio_ratio
        );
    }

    results.push(cw_result);
    results.push(tokio_result);

    results
}

// ============================================================================
// Main
// ============================================================================

fn main() {
    println!("╔══════════════════════════════════════════════════════════════╗");
    println!("║          Clockworker Overhead Benchmarks                     ║");
    println!("╚══════════════════════════════════════════════════════════════╝");
    println!();
    println!("Configuration:");
    println!("  Warmup iterations: {}", WARMUP_ITERS);
    println!("  Bench iterations:  {}", BENCH_ITERS);
    println!();

    // 1A: Spawn throughput
    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    println!("Benchmark 1A: Spawn Throughput");
    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    run_1a();

    // 1B: Yield overhead
    println!("\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    println!("Benchmark 1B: Yield/Poll Overhead");
    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    run_1b();

    // 1C: IO reactor
    println!("\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    println!("Benchmark 1C: IO Reactor Integration");
    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    run_1c();
}