The way you have defined this in mycode
for the timeit
method, all that is going to happen is the function gener
will be defined, not run. You need to run the function in your code block in order to report time taken for execution.
As for what length of time is reasonable (too fast/too slow) it very much depends on what your code is doing. But I suspect you have executed the function in method 2 and only defined it in method 1, hence the discrepancy.
Edit: example code
To illustrate the difference, in the example below the block code1
just defines a function, it does not execute it. The block code2
defines and executes the function.
import timeit
code1 = '''
def gener():
time.sleep(0.01)
'''
code2 = '''
def gener():
time.sleep(0.01)
gener()
'''
We should expect running time.sleep(0.01)
100 times to take approximately 1 second. Running timeit
for code1
returns ~ 10^-5 seconds, because the function gener
is not actually being called:
timeit.timeit(stmt=code1, number=100)
Running timeit
for code2
returns the expected result of ~1 second:
timeit.timeit(stmt=code2, number=100)
Further to this, the point of the setup
argument is to do setup (the parts of the code which are not meant to be timed). If you want timeit
to capture the execution time of gener
, you should use this:
import timeit
setup = '''
def gener():
time.sleep(0.01)
'''
stmt = "gener()"
timeit.timeit(setup=setup, stmt=stmt, number=100)
This returns the time taken to run gener
100 times, not including the time taken to define it.