简体   繁体   English

Python timeit ImportError

[英]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?您如何看待仅导入time并测量computeArea运行前后的时间? Honestly speaking, this chunk of code looks pretty funky from a Python style perspective.老实说,从 Python 风格的角度来看,这段代码看起来很时髦。 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.")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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