0

I am learning basic coding with python 3 using Pycharm.

I am able to use the timeit function in my scripts but i have to put my 'code under test' into an giant string variable to pass to timeit.

is there an easier way to do this and only (for example) pass the name of the 'function under test' to timeit ?

Roshin Raphel
  • 2,612
  • 4
  • 22
  • 40
  • you can use time linux function ex: `time python3 mycode.py` – Jasar Orion Nov 10 '20 at 15:59
  • Does this answer your question? [How do I get time of a Python program's execution?](https://stackoverflow.com/questions/1557571/how-do-i-get-time-of-a-python-programs-execution) – Tomerikoo Nov 10 '20 at 17:02

1 Answers1

3

The answer to whether you can pass the name of a function you have defined to timeit is yes. Copying-pasting from the documentation:

To give the timeit module access to functions you define, you can pass a 
setup parameter which contains an import statement:

def test():
    """Stupid test function"""
    L = [i for i in range(100)]

if __name__ == '__main__':
    import timeit
    print(timeit.timeit("test()", setup="from __main__ import test"))

Depending on your needs, you may:

  • a. want to take a look at the note in the documentation about timeit() temporarily turning off garbage collection during the timing (and how to re-enable it) and,
  • b. consider using a time decorator, you can find many examples online (see, for instance, Python time measure function or Decorator for timeit.timeit method?).
Cyrille Pontvieux
  • 2,356
  • 1
  • 21
  • 29
Nikolaos Chatzis
  • 1,947
  • 2
  • 8
  • 17
  • im confused with the setup = "...", are we actually importing my function 'test' into the timeit function here? it seems to me that my program is the main program and any function that i define is then global (e.g. accessible) to any modules that i import. what am i misunderstanding? – Cool Pontiac Nov 11 '20 at 16:09
  • `timeit` creates a `Timer` instance. Now, check the docs for `class timeit.Timer`, i.e., "The constructor takes a statement to be timed ...". What this piece says is that the statement executed by the `Timer` is, by default, executed in its own namespace which does not have access to the outer namespaces nor it modifies them. Check also "Another option is to pass globals() to the globals parameter, which will cause the code to be executed within your current global namespace. ..." towards the end of the documentation (Python 3.5 and above). – Nikolaos Chatzis Nov 11 '20 at 19:59