【问题标题】:filter takes one calls but it didn't takes time过滤器需要一个电话,但不需要时间
【发布时间】:2014-07-18 13:24:09
【问题描述】:

我正在使用 cProfile 检查过滤器的性能,

cProfile.run("""
s = [range(10000) for i in range(10000)]
filter(None, map(lambda x:x[0], s))""")
         20005 function calls in 42.272 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    2.467    2.467   42.272   42.272 <string>:2(<module>)
    10000    0.004    0.000    0.004    0.000 <string>:3(<lambda>)
        1    0.000    0.000    0.000    0.000 {filter}
        1    0.201    0.201    0.205    0.205 {map}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
    10001   39.599    0.004   39.599    0.004 {range}

从上面的分析中我观察到过滤器,它调用了一次但没有花费时间,为什么它没有花费时间?

【问题讨论】:

  • filter 在 Python2 和 Python3 上的工作方式不同,那么你在哪个上运行呢?
  • @gnibbler 我用过python2.7

标签: python python-2.7 python-3.x filter


【解决方案1】:

如果有函数调用,调用那个函数会有一些时间消耗。

那个时间可能很分钟,小于毫秒。

在您的 Cprofile Test 中,可以表示的最大时间单位是 1 毫秒。

如果一个函数花费的时间少于 1 毫秒,Cprofile 会将其显示为 0 毫秒。

这意味着这里的过滤器需要更少的毫秒,我通过以下方式测试您的代码发现了这一点。

import datetime

l= [range(4) for i in range(4)]
a = datetime.datetime.now()
filter(None, l)
b = datetime.datetime.now()
c = b - a
print c.seconds
print c.microseconds

Output on my system

0
35

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-15
    • 1970-01-01
    • 2017-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多