Pass python script directly to python -m timeit

40 Views Asked by At

According to the offical documentation of timeit, I can time simple python snippets using the command line interface as follows

python3 -m timeit -n 5 "'-'.join(str(n) for n in range(100))"

I can also execute a python3 script named script.py by running

python3 script.py

Because of this I assumed I would be able to do something like this

python3 -m timeit -n 5 script.py

but this does not work.

script.py is not a module so some suggestions along the lines of

python3 -m timeit -n 5 -s 'import script(.py)'

do not work either.

I am a bit out of ideas how I could accomplish my goal, thus my question is

Is there any good option to measure the run time of an python script using python3 -m timeit directly from the command line?

Also, I do not want to do things like:

  • using the time command in linux
  • import the timeit module in my python script itself

Already thanks for your suggestions.

2

There are 2 best solutions below

0
Brusooo On

Try this one

python3 -m timeit -r 1 -s "import subprocess" "subprocess.run(['python3', 'script_name.py'])"
0
Behnam On

The easiest approach that comes to my mind is to execute script.py using os.system("python3 script.py")). So:

python3 -m timeit -n 5 -s "import os; os.system('python3 script.py')"