在python中获得更精确的计时器
给定这个示例代码:
start = time.clock()
while (abs(x**2 - userInput) > epsilon):
x = 0.5 * (x + (userInput/x))
count = count+1
end = time.clock()
print(end-start)
并且考虑到这个操作只需要很少的时间,我怎样才能获得更精确的计时器?
我查看了 timeit 模块,但不知道如何使用它或者它是否是我想要的。
Given this example code:
start = time.clock()
while (abs(x**2 - userInput) > epsilon):
x = 0.5 * (x + (userInput/x))
count = count+1
end = time.clock()
print(end-start)
And given that this operation, take very little time, how can I get a more precise timer?
I have looked at timeit
module but could not figure out how to use it or whether it is what I want.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 timeit 很简单。 Timer 实例采用两个字符串,第一个包含计时操作,第二个包含在计时开始之前执行一次的设置操作。下面的代码应该可以工作,只需将变量值更改为您想要的任何值即可。
这将默认运行您的代码一百万次,并返回运行所需的总时间(以秒为单位)。您可以通过将数字传递给
timeit()
来运行它不同的次数。Using timeit is simple. A Timer instance takes two strings, the first containing the operations to time, and the second containing setup operations that are performed once before timing begins. The following code should work, just change the variable values to whatever you want.
This will run your code a default of one million times and return the total time in seconds it took to run. You can run it a different number of times by passing a number into
timeit()
.我没有将这种方式与 timeit 进行比较,但有时我使用日期时间减法来实现快速而肮脏的计时。回家后我会进行一些测试并进行比较。
结果是:
I haven't compared this way to timeit but sometimes i use datetime subtractions for quick and dirty timing. I'll run some tests when i get home and compare.
results in: