Metadata-Version: 2.4
Name: naptime
Version: 1.0.0
Summary: naptime is a Python library to provide sub-millisecond sleep accuracy.
Author-email: Ben Boudaoud <bboudaoud@nvidia.com>, Peter Xenopoulos <pxenopoulos@nvidia.com>
License-Expression: Apache-2.0
License-File: LICENSE
Requires-Python: >=3.10
Description-Content-Type: text/markdown

# naptime

**Sub-millisecond sleep accuracy for Python.**

## Why naptime?

Python's built-in `time.sleep()` guarantees a *minimum* sleep duration, but
frequently overshoots the target — sometimes by several milliseconds. For
applications that need precise timing, that difference matters.

naptime solves this with a hybrid strategy:

1. **OS sleep** handles the bulk of the wait, keeping CPU usage low.
2. **Busy-wait** (`time.perf_counter()`) takes over for the final
   microseconds, delivering the accuracy that `time.sleep()` cannot.

The crossover point is configurable, so you can tune the trade-off between
accuracy and CPU cost. naptime has **zero dependencies** and supports
**Python 3.10+**.

## Installation

```bash
pip install naptime
```

or

```bash
uv add naptime
```

## Usage

### Drop-in replacement for `time.sleep()`

```python
import naptime

# Sleep for 500 ms — works just like time.sleep(),
# but with much better accuracy.
naptime.sleep(0.5)
```

### Get the actual elapsed time

`naptime.sleep()` returns the actual time slept (in seconds):

```python
actual = naptime.sleep(0.1)
print(f"Requested 100 ms, actually slept {actual * 1000:.2f} ms")
```

### Tune accuracy vs. CPU usage

The `wait_threshold_s` parameter controls when naptime switches from OS sleep
to busy-waiting. A larger threshold means more time spent busy-waiting (higher
accuracy, higher CPU usage):

```python
# Busy-wait the last 20 ms instead of the default 10 ms
naptime.sleep(0.1, wait_threshold_s=0.02)
```

### Pure busy-wait

For the tightest timing requirements you can bypass OS sleep entirely:

```python
# Busy-wait for 50 ms
naptime.busy_wait(0.05)
```

### Full API reference

```python
naptime.MIN_SLEEP_TIME  # Platform default: 1 ms (Linux/macOS), 4 ms (Windows)

naptime.sleep(
    seconds,                        # Duration to sleep (s)
    wait_threshold_s=0.01,          # Switch to busy-wait below this (s)
    min_sleep_time=MIN_SLEEP_TIME,  # Floor for OS sleep calls (s)
    busy_wait_interval=None,        # Optional sleep inside the busy loop (s)
) -> float                          # Actual elapsed time (s)

naptime.busy_wait(
    seconds,          # Duration to busy-wait (s)
    interval=None,    # Optional sleep inside the loop (s)
) -> float            # Actual elapsed time (s)
```

## License

naptime is licensed under the [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0).

Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES.
