File: async_experiment_3.py

package info (click to toggle)
python-pyinstrument 5.1.1%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,620 kB
  • sloc: python: 6,713; ansic: 897; makefile: 46; sh: 20; javascript: 18
file content (46 lines) | stat: -rw-r--r-- 840 bytes parent folder | download
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
import asyncio
import time

import trio

import pyinstrument


def do_nothing():
    pass


def busy_wait(duration):
    end_time = time.time() + duration

    while time.time() < end_time:
        do_nothing()


async def say(what, when, profile=False):
    if profile:
        p = pyinstrument.Profiler()
        p.start()
    else:
        p = None

    busy_wait(0.1)
    sleep_start = time.time()
    await trio.sleep(when)
    print(f"slept for {time.time() - sleep_start:.3f} seconds")
    busy_wait(0.1)

    print(what)
    if p:
        p.stop()
        p.print(show_all=True)


async def task():
    async with trio.open_nursery() as nursery:
        nursery.start_soon(say, "first hello", 2, True)
        nursery.start_soon(say, "second hello", 1, True)
        nursery.start_soon(say, "third hello", 3, True)


trio.run(task)