如果您将代码放入函数中,则可以使用
%time
(带有单个 %
)和选项 -o function()
来获取结果
variable = %time -o function()
例如
def function():
for x in range(1_000_000):
x**2
variable = %timeit -o function()
print(f'{variable.average:.3} s')
如果您使用
print( dir(variable) )
那么您会看到可以从 variable
获得哪些其他值
['__class__',
'__delattr__',
'__dict__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__le__',
'__lt__',
'__module__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'__weakref__',
'_precision',
'_repr_pretty_',
'all_runs',
'average',
'best',
'compile_time',
'loops',
'repeat',
'stdev',
'timings',
'worst']