【问题标题】:Get average run time from `%timeit` ipython magic从 `%timeit` ipython 魔术获取平均运行时间
【发布时间】:2016-02-13 05:13:20
【问题描述】:

尝试对不同的随机函数计时,以查看从列表中选择随机项目的最快方法。 %timeit 想给我“最好的 3 次”最快时间,但由于运行是随机的,访问时间差异很大(从列表后面抓取会很慢;从前面抓取会很快)。

如何获得所有循环的平均值,而不是最好的?

a = [0,6,3,1,3,9,4,3,2,6]

%timeit random.choice(a)
%timeit a[random.randint(0,len(a)-1)]
%timeit a[np.random.randint(0,len(a)-1)]
%timeit np.random.choice(a,1)[0]

当前输出(确认时间变化):

%timeit random.choice(a)
The slowest run took 9.87 times longer than the fastest. This could mean that an intermediate result is being cached 
1000000 loops, best of 3: 1.23 µs per loop

更新:kludge 方法:

%time for i in range(100000): random.choice(a)
%time for i in range(100000): a[random.randint(0,len(a)-1)]
%time for i in range(100000): a[np.random.randint(0,len(a)-1)]
%time for i in range(100000): np.random.choice(a,1)[0]

【问题讨论】:

  • “尝试对不同的随机函数计时,以查看从列表中选择随机项目的最快方式。” -- 这种(可能)抢先式微优化会让你一事无成。
  • @Kay 我正在模拟由数千万个节点组成的网络上的随机游走。我保证——即使是很小的差异也会很重要。目前,随机抽奖占我运行时间的 60%。 (不,这不是先发制人——我正在疯狂地分析)
  • 您是否尝试过从 numpy 数组而不是列表中绘制?我认为np.random.choicea 转换为一个数组,这可能非常昂贵。我看到 len(10) 列表与数组的差异约为 6 倍。
  • 嗯——别以为我能做到。我有一个 c 编译函数给我列表作为实际程序中的输入,我刚刚创建了 a 列表作为示例。但感谢您的思考!

标签: python ipython timeit


【解决方案1】:

你可以使用timeit.repeat:

import timeit
import numpy as np

reps = timeit.repeat(repeat=3, n=10000,
                     stmt="np.random.choice(a)",
                     setup="import numpy as np; a=[0,6,3,1,3,9,4,3,2,6]")

# taking the median might be better, since I suspect the distribution of times will
# be heavily skewed
avg = np.mean(reps)

一个潜在的问题是您可能会遇到缓存效果,这可能会使您的计时变得不那么有意义(see here)。例如,您可能希望使用 setup= 参数在每次迭代中生成一个新的随机列表。

【讨论】:

    【解决方案2】:

    有多快

    random_fd = open('/dev/urandom', 'rb')
    
    a = array.array('I')
    a.read(random_fd, 10**8)
    
    get_next_rand = iter(a).next
    

    为你?如果这是您的瓶颈,我会立即生成大量随机数。

    在我的旧电脑中:

    %timeit array.array('I').read(open('/dev/urandom', 'rb'), 10**6)
    1 loop, best of 3: 200 ms per loop
    

    【讨论】:

    • 这是个好主意。之后我需要调整它们——我从中采样的每个列表的长度都不同——但生成从 0-1、长度倍数并舍入为整数的随机浮点数可能仍然更有效。谢谢!
    • 不客气!请确保在使用模数时不要引入偏差:stackoverflow.com/q/10984974/416224
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多