fork download
  1. from timeit import timeit
  2.  
  3. function = "def f(x): pass\n"
  4. loop = "for x in range(1000):\n"
  5. call = " f(x)"
  6.  
  7. # execute each test 10,000 times
  8. params = { 'number' : 10000, 'globals': globals() }
  9.  
  10. # execution times are in seconds
  11.  
  12. # create the function before the loop
  13. print(timeit(f'{function}{loop}{call}', **params))
  14. # create the function inside the loop
  15. print(timeit(f'{loop} {function}{call}', **params))
  16.  
Success #stdin #stdout 2.01s 9764KB
stdin
Standard input is empty
stdout
0.7576045766472816
1.231069166213274