计时Python。它是如何运作的?
我想对一个函数进行计时,并且想使用 timeit 库。我在网上找不到任何好的例子。我必须对 maxcut 库中的函数“largest_eigenvector”进行计时,该函数将图 G 作为输入,该图 G 由 networkx 库中的函数返回。
所以我想对这段代码进行计时:
import maxcut as mc
import networkx as nx
G = nx.complete_graph(3)
mc.largest_eigenvector(G)
它显然工作得很好。相比之下,我这样做了:
s = """
import maxcut as mc
import networkx as nx
G = nx.complete_graph(3)
"""
t = timeit.Timer(s, 'mc.largest_eigenvector(G)')
但它说: UnboundLocalError:在赋值之前引用局部变量“mc”
我不知道为什么。请有人帮忙,这只是一个语法问题,我找不到合适的文档。
I want to time a function and I'd like to use the timeit library. I can't find any good example on the net. I have to time the function "largest_eigenvector" which is in the maxcut library, this function takes as input a graph G wich is returned by a function in the networkx library.
So I want to time this block of code:
import maxcut as mc
import networkx as nx
G = nx.complete_graph(3)
mc.largest_eigenvector(G)
It obviously works fine. Than to time it I did this:
s = """
import maxcut as mc
import networkx as nx
G = nx.complete_graph(3)
"""
t = timeit.Timer(s, 'mc.largest_eigenvector(G)')
But it says:
UnboundLocalError: local variable 'mc' referenced before assignment
I don't know why. Please someone help it's just a syntax problem and I can't find a decent documentation for this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您已经交换了声明和设置。以相反的方式将参数传递给 Timer()。
You have statement and setup swapped. Pass the arguments to Timer() the other way round.
尝试一下:
以下方法也可能有效:
Try this:
The following might work, too: