简体   繁体   中英

Python timeit ImportError

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)

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.")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM