Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting "TypeError: 'module' is not callable" when calculating execution time with timeit

Tags:

python

timeit

I am trying to calculate the timings of my python code but I keep getting:

TypeError - 'module' is not callable

import timeit
timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)

The link I am checking is this - https://docs.python.org/2/library/timeit.html

I would expect to see the time that took the code to run.

like image 959
Jonas Palačionis Avatar asked Jul 21 '26 13:07

Jonas Palačionis


1 Answers

Did you perhaps name your file as timeit.py?

$ cat timeit.py
import timeit
timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)

$ python3 timeit.py
Traceback (most recent call last):
  File "timeit.py", line 1, in <module>
    import timeit
  File "/path/to/timeit.py", line 2, in <module>
    timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
TypeError: 'module' object is not callable

You have to rename your file to something else (ex. mytimeit.py).
Otherwise import will import your timeit instead of the real timeit module.

You can check the import-ed module with print(timeit.__file__).

$ cat timeit.py
import timeit
print(timeit.__file__)

timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)

$ pwd
/work/scratch

$ python timeit.py
/work/scratch/timeit.py
Traceback (most recent call last)
...

Also, if you want to see "the time that took the code to run", you have to print it.

$ mv timeit.py mytimeit.py
$ cat mytimeit.py
import timeit
print(timeit.__file__)
print(timeit.timeit('"-".join(str(n) for n in range(100))', number=10000))

$ python3 mytimeit.py 
/usr/lib/python3.6/timeit.py
0.1469665479962714
like image 102
Gino Mempin Avatar answered Jul 23 '26 03:07

Gino Mempin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!