的返回值时间!时间一般还是最好?

2024-05-01 18:02:58 发布

您现在位置:Python中文网/ 问答频道 /正文

doc清楚地告诉我们timeit命令行界面输出的最好。在

python -m timeit '"-".join(map(str, range(100)))'
10000 loops, best of 3: 25.2 usec per loop

Python接口呢?在

^{pr2}$

还是最好的吗?在


Tags: of命令行loopmapdoc界面rangebest
2条回答

命令行将repeat选项设置为3:

-r N,  repeat=N

how many times to repeat the timer (default 3)

“最好的”是这三个中最好的。这与number参数不同,当您不设置-n / number参数时,它会自动为您确定。在

另一方面,timeit.timeit()函数不重复。它运行语句number,并给出总时间。从^{} documentation

Create a Timer instance with the given statement, setup code and timer function and run its timeit() method with number executions.

^{}

Time number executions of the main statement. This executes the setup statement once, and then returns the time it takes to execute the main statement a number of times, measured in seconds as a float.

如果您想从中获得最佳结果,请使用^{} function

 timeit.repeat(stmt='pass', setup='pass', timer=<default timer>, repeat=3, number=1000000)

Create a Timer instance with the given statement, setup code and timer function and run its repeat() method with the given repeat count and number executions.

但是,使用timeit.repeat()将不会为您自动设置编号。为此,您必须创建自己的Timer()实例。在

文档链接到implementation,因此您可以在main()函数中看到这是如何完成的;将其简化为使用默认选项时执行的代码:

t = Timer(stmt, setup, timer)
repeat = 3
for i in range(1, 10):
    number = 10**i
    x = t.timeit(number)
    if x >= 0.2:
        break
r = t.repeat(repeat, number)
best = min(r)
print "%d loops," % number,
usec = best * 1e6 / number
if usec < 1000:
    print "best of %d: %.*g usec per loop" % (repeat, 3, usec)
else:
    msec = usec / 1000
    if msec < 1000:
        print "best of %d: %.*g msec per loop" % (repeat, 3, msec)
    else:
        sec = msec / 1000
        print "best of %d: %.*g sec per loop" % (repeat, 3, sec)

在Python3中,通过使用新的^{} method和更好的缩放处理,上述功能得到了很大的改进。在

使用您的声明和设置进行演示:

^{pr2}$

manual:它运行主语句number次(默认为1000000), 并返回执行所有number次所用的时间总和。在

您可以将number=10**8添加到调用中,并查看结果如何更改:

>>> import timeit
>>> timeit.timeit('char in text', setup='text = "sample string"; char = "g"')
0.03136014938354492
>>> timeit.timeit('char in text', setup='text = "sample string"; char = "g"', number=10**7)
0.22713899612426758
>>> timeit.timeit('char in text', setup='text = "sample string"; char = "g"', number=10**8)
2.130625009536743
>>> 

相关问题 更多 >