python timeit.timer,Python-类中的Timeit

作者探讨了如何在Python类实例中正确使用timeit模块计时函数遇到的问题,并介绍了stopwatch作为替代工具的简单易用。文章提供了一个实例,展示了如何避免`self`未定义的错误,并提到了两种计时方法的适用场景。
摘要由CSDN通过智能技术生成

I'm having some real trouble with timing a function from within an instance of a class. I'm not sure I'm going about it the right way (never used timeIt before) and I tried a few variations of the second argument importing things, but no luck. Here's a silly example of what I'm doing:

import timeit

class TimedClass():

def __init__(self):

self.x = 13

self.y = 15

t = timeit.Timer("self.square(self.x, self.y)")

try:

t.timeit()

except:

t.print_exc()

def square(self, _x, _y):

print _x**_y

myTimedClass = TimedClass()

Which, when ran, complains about self.

Traceback (most recent call last):

File "timeItTest.py", line 9, in __init__

t.timeit()

File "C:\Python26\lib\timeit.py", line 193, in timeit

timing = self.inner(it, self.timer)

File "", line 6, in inner

self.square(self.x, self.y)

NameError: global name 'self' is not defined

This has to do with TimeIt creating a little virtual environment to run the function in but what do I have to pass to the second argument to make it all happy?

解决方案

if you're willing to consider alternatives to timeit, i recently found the stopwatch timer utility which might be useful in your case. it's really simple and intuitive, too:

import stopwatch

class TimedClass():

def __init__(self):

t = stopwatch.Timer()

# do stuff here

t.stop()

print t.elapsed

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值