| 1 |
# across-realtime.py |
| 2 |
|
| 3 |
import time |
| 4 |
import trio |
| 5 |
import trio.testing |
| 6 |
|
| 7 |
YEAR = 365 * 24 * 60 * 60 # seconds |
| 8 |
|
| 9 |
|
| 10 |
async def task1(): |
| 11 |
start = trio.current_time() |
| 12 |
|
| 13 |
print("task1: sleeping for 1 year") |
| 14 |
await trio.sleep(YEAR) |
| 15 |
|
| 16 |
duration = trio.current_time() - start |
| 17 |
print(f"task1: woke up; clock says I've slept {duration / YEAR} years") |
| 18 |
|
| 19 |
print("task1: sleeping for 1 year, 100 times") |
| 20 |
for _ in range(100): |
| 21 |
await trio.sleep(YEAR) |
| 22 |
|
| 23 |
duration = trio.current_time() - start |
| 24 |
print(f"task1: slept {duration / YEAR} years total") |
| 25 |
|
| 26 |
|
| 27 |
async def task2(): |
| 28 |
start = trio.current_time() |
| 29 |
|
| 30 |
print("task2: sleeping for 5 years") |
| 31 |
await trio.sleep(5 * YEAR) |
| 32 |
|
| 33 |
duration = trio.current_time() - start |
| 34 |
print(f"task2: woke up; clock says I've slept {duration / YEAR} years") |
| 35 |
|
| 36 |
print("task2: sleeping for 500 years") |
| 37 |
await trio.sleep(500 * YEAR) |
| 38 |
|
| 39 |
duration = trio.current_time() - start |
| 40 |
print(f"task2: slept {duration / YEAR} years total") |
| 41 |
|
| 42 |
|
| 43 |
async def main(): |
| 44 |
async with trio.open_nursery() as nursery: |
| 45 |
nursery.start_soon(task1) |
| 46 |
nursery.start_soon(task2) |
| 47 |
|
| 48 |
|
| 49 |
def run_example(clock): |
| 50 |
real_start = time.perf_counter() |
| 51 |
trio.run(main, clock=clock) |
| 52 |
real_duration = time.perf_counter() - real_start |
| 53 |
print(f"Total real time elapsed: {real_duration} seconds") |
| 54 |
|
| 55 |
|
| 56 |
print("Clock where time passes at 100 years per second:\n") |
| 57 |
run_example(trio.testing.MockClock(rate=100 * YEAR)) |
| 58 |
|
| 59 |
print("\nClock where time automatically skips past the boring parts:\n") |
| 60 |
run_example(trio.testing.MockClock(autojump_threshold=0)) |