我想计算python异步性能并仅选择CPU时间成本。
我已经阅读了如何测量-pythons-asyncio-code-performance。
但是异步。Task._step更改为私有,写入C模块
import asyncio
print(asyncio.Task) # _asyncio.Task
print(dir(asyncio.Task))
['__await__', '__class__', '__del__', '__delattr__', '__dir__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__',
'__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__', '_asyncio_future_blocking', '_callbacks', '_coro',
'_exception', '_fut_waiter', '_log_destroy_pending', '_log_traceback', '_loop',
'_must_cancel', '_repr_info', '_result', '_source_traceback', '_state', 'add_done_callback',
'all_tasks', 'cancel', 'cancelled', 'current_task', 'done', 'exception', 'get_loop',
'get_stack', 'print_stack', 'remove_done_callback', 'result', 'set_exception', 'set_result']
我不能破解只使用 py-code,因为我不想失去 c 代码性能。
这样的东西可能简单而有用,
import time
def time_this(func, *args, **kwargs):
st = time.process_time()
func(*args, **kwargs)
return time.process_time() - st
下面是一个例子,
In [1]: import time, asyncio
...:
...: def time_this(func, *args, **kwargs):
...: st = time.process_time()
...: func(*args, **kwargs)
...: return time.process_time() - st
...:
...: print(time_this(asyncio.run, asyncio.sleep(5)))
0.001157819000000007
更新#1:
或者,您可以遵循此方法,编写自己的事件循环策略。