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
|
import sys
import unittest
import asyncio
import contextvars
import functools
import time
import os
import utils
import yappi
async_context_id = contextvars.ContextVar('async_context_id')
async_context_id.set(-1)
def get_async_context_id():
try:
return async_context_id.get()
except LookupError:
return -2
async def run_in_threadpool(copy_contextvars, func, *args, **kwargs):
"""Based on the starlette function of the same name"""
loop = asyncio.get_event_loop()
if copy_contextvars:
# Ensure we run in the same context
child = functools.partial(func, *args, **kwargs)
context = contextvars.copy_context()
func = context.run
args = (child, )
elif kwargs:
func = functools.partial(func, **kwargs)
return await loop.run_in_executor(None, func, *args)
class AsyncUsage(utils.YappiUnitTestCase):
task_count = 5
context_switch_count = 2
duration = 0.2
task_to_profile_name = "task_to_profile"
def test_async_cpu(self):
ttots = self.profile_tasks("cpu")
for ttot in ttots:
# TODO: What is the underlying assumption here by 0.2, I think
# this has implicit trust on machine speed. We need to change this
self.assertLessEqual(ttot, self.duration * 0.2)
# TODO: fix this
@unittest.skipIf(os.name == "nt", "do not run on Windows")
def test_async_wall(self):
ttots = self.profile_tasks("wall")
for ttot in ttots:
self.assertGreaterEqual(ttot, self.duration)
def profile_tasks(self, clock_type):
yappi.set_clock_type(clock_type)
asyncio.run(self.profile_tasks_coroutine())
return self.get_profiling_outputs()
async def profile_tasks_coroutine(self):
yappi.start()
tasks = self.get_tasks()
await asyncio.gather(*tasks)
yappi.stop()
def get_profiling_outputs(self):
fstats = yappi.get_func_stats(
filter={"name": self.task_to_profile_name}
)
#fstats.print_all()
stats = fstats.pop()
#self.assertEqual(
# stats.ncall, self.task_count * self.context_switch_count
#)
averaged_times = [
stats.ttot / self.task_count for _ in range(self.task_count)
]
return averaged_times
def get_tasks(self):
return [
self.task_to_profile(self.duration) for _ in range(self.task_count)
]
@staticmethod
async def task_to_profile(duration: float):
await asyncio.sleep(duration)
class ContextVarsMixin:
task_count: int
duration: float
task_to_profile_name: str
context_switch_count: int
async def profile_tasks_coroutine(self):
yappi.set_tag_callback(get_async_context_id)
await super().profile_tasks_coroutine()
def get_profiling_outputs(self):
ttots = []
for i in range(self.task_count):
fstats = yappi.get_func_stats(
filter={
"tag": i,
"name": self.task_to_profile_name
}
)
stats = fstats.pop()
#self.assertEqual(stats.ncall, self.context_switch_count)
ttots.append(stats.ttot)
return ttots
def get_tasks(self):
async def await_with_context_id(context_id, awaitable):
async_context_id.set(context_id)
return await awaitable
return [
await_with_context_id(i, self.task_to_profile(self.duration))
for i in range(self.task_count)
]
class ThreadTaskMixin:
run_in_threadpool_copy_contextvars = False
task_to_profile_name = "_task_in_thread"
context_switch_count = 1
async def task_to_profile(self, duration: float):
await run_in_threadpool(
self.run_in_threadpool_copy_contextvars, self._task_in_thread,
duration
)
@staticmethod
def _task_in_thread(duration: float):
time.sleep(duration)
class AsyncUsageWithContextvars(ContextVarsMixin, AsyncUsage):
pass
class AsyncUsageThreaded(ThreadTaskMixin, AsyncUsage):
pass
class AsyncUsageThreadedWithContextvars(
ThreadTaskMixin, ContextVarsMixin, AsyncUsage
):
run_in_threadpool_copy_contextvars = True
class AsyncUsageThreadedWithContextvarsSelfContained(utils.YappiUnitTestCase):
task_count = 5
context_switch_count = 1
duration = 0.2
task_to_profile_name = "_task_in_thread"
def test_async_cpu(self):
ttots = self.profile_tasks("cpu")
for ttot in ttots:
self.assertLessEqual(ttot, self.duration * 0.1)
def test_async_wall(self):
ttots = self.profile_tasks("wall")
for ttot in ttots:
self.assertGreaterEqual(ttot, self.duration)
def profile_tasks(self, clock_type):
yappi.set_clock_type(clock_type)
asyncio.run(self.profile_tasks_coroutine())
return self.get_profiling_outputs()
async def profile_tasks_coroutine(self):
yappi.set_tag_callback(get_async_context_id)
yappi.start()
tasks = self.get_tasks()
await asyncio.gather(*tasks)
yappi.stop()
def get_profiling_outputs(self):
ttots = []
for i in range(self.task_count):
fstats = yappi.get_func_stats(
filter={
"tag": i,
"name": self.task_to_profile_name
}
)
stats = fstats.pop()
#self.assertEqual(stats.ncall, self.context_switch_count)
ttots.append(stats.ttot)
return ttots
def get_tasks(self):
async def await_with_context_id(context_id, awaitable):
async_context_id.set(context_id)
return await awaitable
return [
await_with_context_id(i, self.task_to_profile(self.duration))
for i in range(self.task_count)
]
async def task_to_profile(self, duration: float):
await run_in_threadpool(
copy_contextvars=True, func=self._task_in_thread, duration=duration
)
@staticmethod
def _task_in_thread(duration: float):
time.sleep(duration)
|