Python timeit ImportError

52 Views Asked by At

I am trying to compute the time my program takes to execute but sometimes it works fine and sometimes I get the following error:

ImportError: cannot import name 'N' from '__main__'
    N = number 

    t = timeit.Timer(
    "computeArea(N, 4)",
    "from __main__ import computeArea, N")        
    computeTime = t.timeit(1)

    print(computeTime)
1

There are 1 best solutions below

1
Mike L On

What do you think of just importing time and measuring the time before and after computeArea runs? Honestly speaking, this chunk of code looks pretty funky from a Python style perspective. Measuring the time yourself is easy, and can be easily modified for more interesting examples (say, taking the average time by timing the same code dozens of times).

import time

start_time = time.time()

# Do anything here. This is a filler.
for i in range(100):
  print(i)

end_time = time.time()
total_time = end_time - start_time

print(f"Program took {total_time} seconds.")