简体   繁体   English

为什么timeit.timeit在使用变量时会出错?

[英]Why timeit.timeit is giving error when using with variable?

I have been trying to execute one code snippet to get to know how much time it takes to execute. 我一直在尝试执行一个代码片段,以了解执行所需的时间。 I had tried two alternatives to do that. 我曾尝试过两种方法来做到这一点。 One is using variable inside timeit.timeit function and check. 一个是在timeit.timeit函数内部使用变量并检查。 And the other one is directly using the value and check. 而另一个是直接使用值和检查。 The second approach is working fine but I am facing some scoping issue while using first one. 第二种方法工作正常但我在使用第一种方法时面临一些范围问题。 Attached are the images for both scenarios. 随附的是两种情景的图像。 使用Variable里面的timeit函数

在timeit中使用Value

Can anyone help me in this regard? 谁可以在这方面帮助我? Any suggestions to the questions are highly appreciated. 对这些问题的任何建议都非常感谢。

Others already addressed the main issue (the code you pass to timeit() is invalid), I just wanted to mention that with the commonly posted solution (adding a semi-colon between the two statements) you will end up benchmarking the total cost of both statements combined (creating the literal string "Hello world" , assigning it to a variable and calling endswith('d') on this variable). 其他人已经解决了主要问题(你传递给timeit()的代码是无效的),我只是想提一下使用常用的解决方案(在两个语句之间添加一个分号),你最终会对总成本进行基准测试。两个语句组合在一起(创建文字字符串"Hello world" ,将其分配给变量并在此变量上调用endswith('d') )。 Assuming what you're actually interested in is the cost of the second statement only, you may want to use timeit() second's (optional) "setup" argument with is a piece of code to be executed before the execution of the tested code, ie: 假设你真正感兴趣的只是第二个语句的成本,你可能想要使用timeit() second(可选)“setup”参数,它是在执行测试代码之前要执行的一段代码,即:

import timeit
timeit.timeit("s.endwith('d')", "s = 'Hello World'", number=10000)

which will execute both statements but only benchmark the first one. 这将执行两个语句,但只对第一个语句进行基准测试。

This is also useful if you want to benchmark a function imported from a module: 如果要对从模块导入的函数进行基准测试,这也很有用:

timeit.timeit("re.search(r'42', 'hello world')", "import re")

or from your current script or interactive shell session: 或者从您当前的脚本或交互式shell会话中:

$ python
Python 3.6.5 (default, Apr  1 2018, 05:46:30) 
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def foo():
>>>    return 42
>>> import timeit
>>> timeit.timeit("foo()", "from __main__ import foo")

I'm going to guess you do not have that much experience programming in python, otherwise the SyntaxError would have been clear enough. 我猜你在python中没有那么多编程经验,否则SyntaxError就足够清楚了。 The exception given states that the syntax (ie. lines of code) is invalid. 给出的例外声明语法(即代码行)无效。

Valid ( Compound statement ) code. 有效( 复合语句 )代码。 But harder to read so not advised: 但更难阅读所以不建议:

s='Hello world'; s.endswith('d')

Invalid code: 无效的代码:

s='Hello world'  s.endswith('d')

The latter would raise an exception, which will try to highlight the exact location of where the exception is caused with an '^'. 后者会引发一个异常,它会尝试用'^'突出显示异常的确切位置。

s='Hello world'  s.endswith('d')
  File "<stdin>", line 1
    s='Hello world'  s.endswith('d')
                     ^
SyntaxError: invalid syntax

For testing small bits of code with timeit, you could put the code into a function and call that. 为了使用timeit测试少量代码,您可以将代码放入函数中并调用它。 For example: 例如:

import timeit

def test():
    s = 'Hello world'
    s.endswith('d')


if __name__ == '__main__':
    t = timeit.Timer('test()', setup='from __main__ import test')
    num_of_repeat = 1000
    runs = t.repeat(repeat=num_of_repeat, number=1)
    print('Fastest run of {3} repeats: {0}ms  Slowest: {1}ms  Average: {2}ms'.format(
        min(runs) * 1000, max(runs) * 1000, (sum(runs) / float(len(runs))) * 1000, num_of_repeat))

Put this into a file called mytest.py, and run it from commandline: 将它放入名为mytest.py的文件中,并从命令行运行它:

python mytest.py

The issue is that s = 'Hello World' and s.endswith('d') 问题是s = 'Hello World's.endswith('d')

are two separate statements so either they have to be in different lines or they must me separated using a semi-colon 是两个单独的陈述,所以要么他们必须在不同的行或他们必须我用分号分开

So change it to 所以改成它

timeit.timein("s = 'Hello World'; s.endswith('d')",number=10000)

If you want to run several statements you can simply use the triple quotes for your code. 如果要运行多个语句,只需使用代码的三重引号即可。 Example: 例:

import timeit
code = """
s = 'Hello world'
s.endswith('d')
"""
timeit.timeit(code, number=10000)

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

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