我正在图上使用python函数,这是递归且复杂的NP。但是,我在很长的时间内得到了结果,因此我使用了kernprof来查看哪些行花费更多的时间。
我看到这条线比我想的要花更多的时间:
Line # Hits Time Per Hit % Time Line Contents
==============================================================
...
53 120244 740797.0 6.2 17.0 if any( [m[passed].get(i, False) for passed in isom] ): # si ce noeud est lié à un noeud passé, le tester
因此,我选择使用生成器,因为似乎我不应该生成所有列表,因为我只是想知道是否为真。
但是使用发电机,我得到了这个结果:
Line # Hits Time Per Hit % Time Line Contents
==============================================================
...
53 35283 509901.0 14.5 12.8 if any( (m[passed].get(i, False) for passed in isom) ): # si ce noeud est lié à un noeud passé, le tester
所以似乎比列表理解要快,但是我不明白为什么每次点击的时间更长,为什么我的点击次数少得多?
rkern(https://github.com/rkern/line_profiler)的常见问题解答:
为什么当我使用LineProfiler时,我的列表理解命中率如此之高?
LineProfiler为列表理解的每次迭代记录一次具有列表理解的行。
并且这解释了我认为为什么使用生成器的每次命中时间更长的原因,如列表中的很多命中只是返回false的迭代,但是使用生成器时,生成器的命中很多,这要慢一些。