gpt4 book ai didi

python - 在 timeit 中使用分号

转载 作者:太空狗 更新时间:2023-10-29 19:34:18 25 4
gpt4 key购买 nike

当我在作为字符串传递的语句参数中有异常时,我似乎无法让 timeit.timeit 工作:

# after the first and third semicolon, I put 4 spaces 
timeit.timeit('try:; a=1;except:; pass')

这导致:

Traceback (most recent call last):
File "a.py", line 48, in <module>
timeit.timeit('try:; a=1;except:; pass')
File "C:\CPython33\lib\timeit.py", line 230, in timeit
return Timer(stmt, setup, timer).timeit(number)
File "C:\CPython33\lib\timeit.py", line 136, in __init__
code = compile(src, dummy_src_name, "exec")
File "<timeit-src>", line 6
try:; a=1;except:; pass
^
SyntaxError: invalid syntax

我用 Python 3.3 运行它,但即使使用旧的 Python (3.2) 也会发生同样的错误。

更新:

我正在关注 this documentation (强调我的):

class timeit.Timer(stmt='pass', setup='pass', timer=)

Class for timing execution speed of small code snippets.

The constructor takes a statement to be timed, an additional statement used for setup, and a timer function. Both statements default to 'pass'; the timer function is platform-dependent (see the module doc string). stmt and setup may also contain multiple statements separated by ; or newlines, as long as they don’t contain multi-line string literals.

最佳答案

您需要使用换行符而不是分号提供正确缩进的代码。尝试将其更改为以下内容:

timeit.timeit('try:\n    a=1\nexcept:\n    pass')

虽然这可能更具可读性:

stmt = '''\
try:
a=1
except:
pass'''
timeit.timeit(stmt)

分号可以很好地分隔具有相同缩进级别的语句,但是您在分号和下一条语句之间放置的任何空格或制表符都将被忽略,因此您不能将它们与缩进一起使用。

关于python - 在 timeit 中使用分号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10301896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com