在timeit中使用分号 [英] Using semicolons inside timeit

查看:98
本文介绍了在timeit中使用分号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当以字符串形式传递的语句参数中有异常时,我似乎无法使 timeit.timeit 正常工作。

I can't seem to get timeit.timeit to work when I have exceptions in the statement argument passed as string:

# 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),也会发生相同的错误。

I'm running it with Python 3.3, but the same mistake happens even with the old Python (3.2).

更新:

遵循此文档(重点是我):


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

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

用于计时小代码段的执行速度的类。

Class for timing execution speed of small code snippets.

构造函数接受一条要计时的语句,另外一条语句
用于设置,以及计时器功能。这两个语句默认为
通过;计时器功能取决于平台(请参见模块doc
字符串)。 stmt和setup可能还包含多个语句,
以;
或换行符分隔,只要它们不包含多行字符串
文字即可。

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.


推荐答案

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

You need to provide properly indented code with newlines, not semi-colons. Try changing it to the following:

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

尽管这样可能更易读:

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

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

Semicolons will work fine for separating statements that would have the same indentation level, but any spaces or tabs you put between the semicolon and the next statement will be ignored so you cannot use them with indentation.

这篇关于在timeit中使用分号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆