Skip to content

Improve sleep performance and precision#1

Merged
berkgercek merged 1 commit intoberkgercek:mainfrom
mscheltienne:dev
Mar 3, 2026
Merged

Improve sleep performance and precision#1
berkgercek merged 1 commit intoberkgercek:mainfrom
mscheltienne:dev

Conversation

@mscheltienne
Copy link
Contributor

I got Claude to work, I got no clue what it did, I'll let you dissect the changes, have a look:

  Results                                                                                                                               
                                                                                                                                        
  ┌──────────┬──────────┬───────────┬───────────┬──────────────────────────────────────────┐                                            
  │ Duration │  Before  │   After   │  stimuli  │               Improvement                │                                            
  ├──────────┼──────────┼───────────┼───────────┼──────────────────────────────────────────┤
  │ 1μs      │ 4.07μs   │ 1.05μs    │ 1.65μs    │ 3.9x faster (now beats stimuli)          │
  ├──────────┼──────────┼───────────┼───────────┼──────────────────────────────────────────┤
  │ 10μs     │ 12.20μs  │ 10.08μs   │ 10.77μs   │ 1.2x faster (now beats stimuli)          │
  ├──────────┼──────────┼───────────┼───────────┼──────────────────────────────────────────┤
  │ 100μs    │ 102.08μs │ 100.11μs  │ 100.91μs  │ tighter                                  │
  ├──────────┼──────────┼───────────┼───────────┼──────────────────────────────────────────┤
  │ 1ms      │ 1154μs   │ 1000.64μs │ 1003.40μs │ 153μs less overshoot (now beats stimuli) │
  └──────────┴──────────┴───────────┴───────────┴──────────────────────────────────────────┘

  What changed in src/lib.rs

  Three conceptual fixes to the sleepers function:

  1. Instant::now() instead of SystemTime::now() — monotonic clock, appropriate for elapsed time measurement, uses mach_absolute_time()
  on macOS with ~42ns resolution on Apple Silicon
  2. Adaptive halving instead of single coarse sleep — sleep for half the remaining time when >200μs remains, converging safely without
  overshooting
  3. std::hint::spin_loop() instead of thread::sleep(500ns) — pure CPU spin-wait hint (ARM YIELD instruction) for the final <200μs,
  avoiding the OS scheduler entirely

@berkgercek berkgercek merged commit 78a6a95 into berkgercek:main Mar 3, 2026
15 checks passed
@mscheltienne mscheltienne deleted the dev branch March 3, 2026 14:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants