3

I am using the timeit.timeit function to time one of my own functions, but the time returned is in scientific notation.

import timeit

def func():
    ...

print(timeit.timeit(stmt="func()", setup="from __main__ import func", number=100000)/100000)

This returns something like 3.563012266666666e-05. I have used timeit before, but this has never happened. Anyone know why it is doing this?

Have a nice day
  • 1,007
  • 5
  • 11

3 Answers3

3

It's happening because you're dividing it by 1000. If you don't do that then the output looks like this:

>>> print(timeit.timeit(stmt="func()", setup="from __main__ import func", number=100000))
>>> 0.009756448998814449

Python will show any large or small number—under or over a certain range—using scientific notation.

If you want to see the result as before, you can leverage Python's string formatting like this:

>>> t = timeit.timeit(stmt="func()", setup="from __main__ import func", number=100000)/100000
>>> f"{t:.20f}"

Here, the :.20 makes sure that it'll print the number up to 20 decimal places. However, do remember that by doing this, you're converting the float into a string. This will return:

>>> '0.00000009274555020966'
Redowan Delowar
  • 1,580
  • 1
  • 14
  • 36
3

This is likely because your dividing after you retrieve the time. You can format the value when you print it by using f strings (f"{time:.4f}") The .4f tells python to print the value as a floating point with 4 decimal places, you can make that as small or as large as you want to see the number of digits you want.

Lucas Ford
  • 181
  • 3
2

3.563012266666666e-05 is not really exponential form; it's just scientific notation. 3.563012266666666e-05 is equal to 0.00003563012266666666. Scientific notation is used to express either very large or very small numbers.

Jacob Lee
  • 4,405
  • 2
  • 16
  • 37