Reputation: 1
whenever I run the cell the time is coming in microseconds, I want the time in seconds how can I achieve this?
I want time in seconds or how can I get the result in another time parameter like second or minute
Upvotes: -1
Views: 796
Reputation: 142631
Doc for %timeit
If you put code in def function()
then you can use %time
(with single %
)
with option -o function()
to get result in variable
variable = %time -o function()
It doesn't work with double %%
. It raises error when it sees %%
after =
.
For example (all in one cell)
def function():
for x in range(1_000_000):
x**2
variable = %timeit -o function()
print(f'{variable.average:.3} s')
But it still displays original result before your print()
EDIT:
for %%
you can get result in _
in next cell
%%timeit -o
for x in range(1_000_000):
x**2
next cell
print(f'{_.average:.3} s')
But it still displays original result before first cell
You can use %%capture
to hide original result
%%capture
%%timeit -o
for x in range(1_000_000):
x**2
Based on documentation for %%capture you can even use it to assign output to variable but it will be string, not object with .average
, so it will be hard to format it. And it doesn't work for me :/
%%capture original_output
%%timeit -o
for x in range(1_000_000):
x**2
next cell
print(f'{_.average:.3} s')
print(f'original output: {original_output}')
If you use print( dir(variable) )
then you see what other values you can get from variable
and you can use them to format output on your own.
To skip names which start with _
(like __class__
) you can use list comprehension:
[var for var in dir(variable) if not var.startswith('_')]
['all_runs',
'average',
'best',
'compile_time',
'loops',
'repeat',
'stdev',
'timings',
'worst']
EDIT:
Here notebook on nbviewer.org created by @Wayne (see comment below).
To make sure I add also screenshot:
Upvotes: 2