参数超出范围

时间:2016-04-01 04:25:58

标签: python

loops = 25

a = range(1, loops)

def f(x):
    return 3 * log(x) + cos(x) ** 2

使用timeit的最佳方法是什么? 我已经尝试了几次,但经常出错。我希望f次等于循环。

到目前为止,我已经获得了print(timeit.timeit(lambda: f(5))),并且使用了timeit构造函数的参数来填充了一半的错误。

继续进一步。我有另一个类似的例子。

a = np.arange(1, loops)

r = 3 * np.log(a) + np.cos(a) ** 2
#Using 2 instead of a
print(timeit.timeit("3 * np.log(2) + np.cos(2) ** 2", setup="import numpy as np"))

如何将范围a合并到时间的stmt字符串中?

3 个答案:

答案 0 :(得分:1)

Python> = 3.5

  

可选的globals参数指定用于执行代码的命名空间。

     

在版本3.5中更改:添加了可选的globals参数。

https://docs.python.org/3/library/timeit.html#timeit.timeit

>>> import timeit
>>> a = range(1, 1000)
>>> timeit.timeit("sum(a)", globals=globals())
10.732978596999601

Python< 3.5

在setup语句(旧方法)中构建命名空间。

  

stmt和setup也可能包含多个以;分隔的语句;或换行符,只要它们不包含多行字符串文字。

In [2]: setup = """
   ...: a = range(1, 1000)
   ...: """

In [3]: timeit.timeit("sum(a)", setup=setup)
Out[3]: 10.133886003999578

即使它包含多行字符串文字,这似乎也可以正常工作......

In [11]: setup = """
a = '''heh
hoh
hih
'''
def f(x):
    #print(x)
    return len(x)
"""

In [12]: timeit.timeit("f(a)", setup)
Out[12]: 0.08516639499976009

答案 1 :(得分:1)

在Python 2中,您可以使用以下内容:

stmt = "results = list(map(f, a))"

stp = """
import math

def f(x):
    return 3 * math.log(x) + math.cos(x) ** 2

loops = 25
a = xrange(1, loops)
"""

# will apply f to each elmnt of a once
print(timeit.timeit(stmt=stmt, setup=stp, number=1))

答案 2 :(得分:0)

  

如何将范围a合并到时间的stmt字符串中?

使用字符串格式:

loops = 25
setup = "import numpy as np"
statement = "3 * np.log(2) + np.cos(2) ** np.arange(1, %d)" % loops
timeit.timeit(statement, setup=setup)