我正在尝试使用Python中的timeit模块(编辑:我们使用的是Python 3)来决定几个不同的代码流.在我们的代码中,我们有一系列if语句来测试字符串中是否存在字符代码,如果有,则将其替换为:
if "<substring>" in str_var:
str_var = str_var.replace("<substring>", "<new_substring>")
Run Code Online (Sandbox Code Playgroud)
对于不同的子串,我们这样做了很多次.我们在这之间进行辩论并使用像这样的替换:
str_var = str_var.replace("<substring>", "<new_substring>")
Run Code Online (Sandbox Code Playgroud)
我们尝试使用timeit来确定哪一个更快.如果上面的第一个代码块是"stmt1"而第二个是"stmt2",我们的设置字符串看起来像
str_var = '<string><substring><more_string>',
Run Code Online (Sandbox Code Playgroud)
我们的timeit语句如下所示:
timeit.timeit(stmt=stmt1, setup=setup)
Run Code Online (Sandbox Code Playgroud)
和
timeit.timeit(stmt=stmt2, setup=setup)
Run Code Online (Sandbox Code Playgroud)
现在,在我们的两台笔记本电脑上运行它(相同的硬件,类似的处理负载)stmt1(带有if语句的语句)即使在多次运行后也会运行得更快(3-4个百分点,大约四分之一) stmt2的第二个).
但是,如果我们定义函数来做两件事(包括创建变量的设置),如下所示:
def foo():
str_var = '<string><substring><more_string>'
if "<substring>" in str_var:
str_var = str_var.replace("<substring>", "<new_substring>")
Run Code Online (Sandbox Code Playgroud)
和
def foo2():
str_var = '<string><substring><more_string>'
str_var = str_var.replace("<substring>", "<new_substring>")
Run Code Online (Sandbox Code Playgroud)
和运行timeit像:
timeit.timeit("foo()", setup="from __main__ import foo")
timeit.timeit("foo2()", setup="from __main__ import foo2")
Run Code Online (Sandbox Code Playgroud)
没有if语句(foo2)的语句运行得更快,与非功能结果相矛盾.
我们是否遗漏了Timeit的工作原理?或者Python如何处理这样的案例?
编辑这里是我们的实际代码:
>>> def foo():
s = "hi 1 2 3"
s = s.replace('1','5')
>>> …
Run Code Online (Sandbox Code Playgroud) 我想在同一个Python模块中编写多个函数,每个函数都使用一个单独的分析测试timeit
,这样我就可以使用命令行参数来指定运行哪个函数.一个天真的例子(profiling.py)将是:
import sys
import timeit
def foo():
setup = """
import random
"""
foo_1 = """
for i in range(1000):
random.randint(0, 99) + random.randint(0, 99)
"""
foo_2 = """
for i in range(1000):
random.randint(0, 99) + random.randint(0, 99)
"""
foo_3 = """
for i in range(1000):
random.randint(0, 99) + random.randint(0, 99)
"""
print 'foo_1', timeit.Timer(foo_1, setup).timeit(1000)
print 'foo_2', timeit.Timer(foo_2, setup).timeit(1000)
print 'foo_3', timeit.Timer(foo_3, setup).timeit(1000)
if __name__ == '__main__':
if (len(sys.argv) > 1):
if (sys.argv[1] == 'foo'):
foo()
else: …
Run Code Online (Sandbox Code Playgroud) 我正在尝试,python -mtimeit
所以我把python -mtimeit "n = 0; while n < 10: pass"
然后出现了无效的语法错误.与分号和循环相同.
但是,当我尝试分号并单独循环时.两者都很好.
python -c "for i in range(10): print(n)"
python -c "n = 1; n = 2; print(n)"
Run Code Online (Sandbox Code Playgroud)
为什么会如此?如何在timeit中测试while循环?非常感谢你!
我使用以下代码将24位二进制文件加载data
到16位数numpy
组中:
temp = numpy.zeros((len(data) / 3, 4), dtype='b')
temp[:, 1:] = numpy.frombuffer(data, dtype='b').reshape(-1, 3)
temp2 = temp.view('<i4').flatten() >> 16 # >> 16 because I need to divide by 2**16 to load my data into 16-bit array, needed for my (audio) application
output = temp2.astype('int16')
Run Code Online (Sandbox Code Playgroud)
我想可以提高速度效率,但是如何?
我只是在 python 中玩timeit
,下面的代码工作正常:
def mysleep(n):
import time
time.sleep(n)
import timeit
for k in range (1,5):
def mytime():
mysleep(k)
t1 = timeit.Timer("mytime();", "from __main__ import mytime")
print k, t1.timeit(1)
Run Code Online (Sandbox Code Playgroud)
但如果我将相同的代码放入一个函数中,则每次的k
时间约为 3 秒。
def mytest():
import timeit
for k in range (1,5):
def mytime():
mysleep(k)
t1 = timeit.Timer("mytime();", "from __main__ import mytime")
print k, t1.timeit(1)
mytest()
Run Code Online (Sandbox Code Playgroud)
为什么我的函数内的代码不起作用以及如何修复它?
我正在尝试使用timeit.timeit来查找执行特定代码行所需的时间.问题是这一行包含变量,我需要以某种方式导入它们,所以我的问题是如何?为了更清楚,代码看起来像这样:
def func():
var1 = 'aaa'
var2 = 'aab'
t1 = timeit.timeit('var1==var2', 'from __main__ import ___', number = 10**4) # here I'm missing what to put after the import
Run Code Online (Sandbox Code Playgroud)
如果我试图在这个代码中执行此代码,__main__
我会直接使用'from __main__ import var1, var2'
Any解决方案导入变量吗?
我是使用 timeit 模块的新手,我很难让多行代码片段在 timeit 内运行。
什么工作:
timeit.timeit(stmt = "if True: print('hi');")
Run Code Online (Sandbox Code Playgroud)
什么不起作用(这些都无法运行):
timeit.timeit(stmt = "if True: print('hi'); else: print('bye')")
timeit.timeit(stmt = "if True: print('hi') else: print('bye')")
timeit.timeit(stmt = "if True: print('hi');; else: print('bye')")
Run Code Online (Sandbox Code Playgroud)
我发现我可以使用三引号来封装多行代码段,但我宁愿只在一行上输入。
有没有办法在 timeit 的一行中使用 else 语句?
我正在尝试使用IPython magic命令%%timeit
,但遇到了一些问题。我尝试计时的块未返回我在其中定义的变量。
具体来说,假设我想衡量将变量var设置为30需要多长时间。
%%timeit
var = 5 * 6
Run Code Online (Sandbox Code Playgroud)
运行此块,我得到类似的信息16.8 ns ± 0.303 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)
。当我以后尝试调用var时,我得到了NameError: name 'var' is not defined
。
我发现了这个问题,但是,我不确定该如何处理。另外,这是从2014年开始的,因此我认为可能会有一些变化。
有没有一种方法可以“保留”在块中定义的变量,%%timeit
以便以后可以调用它?
我正在使用Python 3.6,Anaconda 4.4.10。
要复制现有列表中的嵌套列表,遗憾的是仅仅将其相乘是不够的,否则将创建引用而不是列表中的独立列表,请参阅此示例:
x = [[1, 2, 3]] * 2
x[0] is x[1] # will evaluate to True
Run Code Online (Sandbox Code Playgroud)
为了实现目标,您可以在列表推导中使用范围函数,例如,请参阅:
x = [[1, 2, 3] for _ in range(2)]
x[0] is x[1] # will evaluate to False (wanted behaviour)
Run Code Online (Sandbox Code Playgroud)
这是一种在不创建引用的情况下将列表中的项目相乘的好方法,并且在许多不同的网站上也对此进行了多次解释.
但是,有一种更有效的方法来复制列表元素.那个代码对我来说似乎有点快(通过命令行的timeit测量,并且对于下面的代码和上面代码中的范围(n),使用不同的参数n∈{1,50,100,10000}):
x = [[1, 2, 3] for _ in [0] * n]
Run Code Online (Sandbox Code Playgroud)
但我想知道,为什么这段代码运行得更快?还有其他缺点(更多内存消耗或类似情况)?
python -m timeit '[[1, 2, 3] for _ in range(1)]'
1000000 loops, best of 3: 0.243 usec per loop
python -m timeit '[[1, 2, 3] for _ in range(50)]'
100000 …
Run Code Online (Sandbox Code Playgroud) 我timeit
在Python中玩过,遇到了一个奇怪的问题。
我定义一个简单的函数add
。 timeit
当我传递add
两个字符串参数时,可以工作。但是ValueError: stmt is neither a string nor callable
当我传递add
两个int
参数时,它会增加。
>>> import timeit
>>> def add(x,y):
... return x + y
...
>>> a = '1'
>>> b = '2'
>>> timeit.timeit(add(a,b))
0.01355926995165646
>>> a = 1
>>> b = 2
>>> timeit.timeit(add(a,b))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/anaconda/lib/python3.6/timeit.py", line 233, in timeit
return Timer(stmt, setup, timer, globals).timeit(number)
File "/anaconda/lib/python3.6/timeit.py", …
Run Code Online (Sandbox Code Playgroud)