Title: Timeit Python. How does it work?
Tags: python;syntax;timer;timeit
Question: 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.


Here is another answer: You have statement and setup swapped. Pass the arguments to Timer() the other way round.

Here is another answer: 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)')
Comment for this answer: It works fine your solution thanks..:) But is there a more elegant way to do this?

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2011:00:11/02/11', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<python><syntax><timer><timeit>', 'Title': 'Timeit Python. How does it work?', 'ViewCount': 1100, 'id': 7978892, 'user_AboutMe': '<p>Just another guy studying computer science.</p>\n', 'user_AccountId': 918344.0, 'user_DisplayName': 'blueSurfer', 'user_Reputation': 5376.0, 'user_Views': 261.0, 'user_id': 950625.0}}