简体   繁体   English

timeit.timeit 以科学计数法返回时间?

[英]timeit.timeit returning time in scientific notation?

I am using the timeit.timeit function to time one of my own functions, but the time returned is in scientific notation.我正在使用timeit.timeit function 来计时我自己的功能之一,但返回的时间是科学计数法。

import timeit

def func():
    ...

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

This returns something like 3.563012266666666e-05 .这将返回类似3.563012266666666e-05 I have used timeit before, but this has never happened.我以前使用过timeit ,但这从未发生过。 Anyone know why it is doing this?任何人都知道它为什么这样做?

It's happening because you're dividing it by 1000. If you don't do that then the output looks like this:这是因为你将它除以 1000。如果你不这样做,那么 output 看起来像这样:

>>> 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. Python 将使用科学计数法显示任何大小(低于或超过一定范围)。

If you want to see the result as before, you can leverage Python's string formatting like this:如果您想像以前一样查看结果,可以像这样利用 Python 的字符串格式:

>>> 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.在这里, :.20确保它将打印最多小数点后 20 位的数字。 However, do remember that by doing this, you're converting the float into a string.但是,请记住,通过这样做,您将浮点数转换为字符串。 This will return:这将返回:

>>> '0.00000009274555020966'

3.563012266666666e-05 is not really exponential form; 3.563012266666666e-05并不是真正的指数形式; it's just scientific notation.这只是科学记数法。 3.563012266666666e-05 is equal to 0.00003563012266666666 . 3.563012266666666e-05等于0.00003563012266666666 Scientific notation is used to express either very large or very small numbers.科学记数法用于表示非常大或非常小的数字。

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.您可以在使用 f 字符串 (f"{time:.4f}") 打印值时对其进行格式化。 .4f告诉 python 将值打印为具有 4 位小数的浮点数,您可以将其设为小数或大到你想看到你想要的位数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM