计时Python。它是如何运作的?

发布于 2024-12-13 09:27:11 字数 564 浏览 0 评论 0原文

我想对一个函数进行计时,并且想使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

行至春深 2024-12-20 09:27:11

您已经交换了声明和设置。以相反的方式将参数传递给 Timer()。

You have statement and setup swapped. Pass the arguments to Timer() the other way round.

古镇旧梦 2024-12-20 09:27:11

尝试一下:

def tmp():
    import maxcut as mc 
    import networkx as nx 
    G = nx.complete_graph(3)
    mc.largest_eigenvector(G)

t = timeit.Timer(s, 'tmp()')

以下方法也可能有效:

t = timeit.Timer(setup=s, stmt='mc.largest_eigenvector(G)')

Try this:

def tmp():
    import maxcut as mc 
    import networkx as nx 
    G = nx.complete_graph(3)
    mc.largest_eigenvector(G)

t = timeit.Timer(s, 'tmp()')

The following might work, too:

t = timeit.Timer(setup=s, stmt='mc.largest_eigenvector(G)')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文