Python-类中的Timeit [英] Python - Timeit within a class

查看:179
本文介绍了Python-类中的Timeit的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从类的实例中计时函数时,我遇到了一些麻烦.我不确定我是否会以正确的方式进行操作(之前从未使用过timeIt),并且尝试了第二个参数导入内容的一些变体,但没有运气.这是我正在做的一个愚蠢的例子:

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 "<timeit-src>", line 6, in inner
    self.square(self.x, self.y)
NameError: global name 'self' is not defined

这与TimeIt有关,它创建了一个小的虚拟环境来运行该函数,但是我必须传递给第二个参数以使其全部满意吗?

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?

推荐答案

如果您愿意考虑使用timeit的替代方法,我最近发现了

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

这篇关于Python-类中的Timeit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆