代码的速度或风格/紧凑性会更好吗?

时间:2017-04-24 06:39:54

标签: performance python-3.x class optimization

我意识到答案会因代码的情况和目的而有所不同。我在一个模块中编写了一个类,并意识到重新定义类的操作符方法需要花费大量代码。我们为类本身使用继承,为什么不使用方法?当然,它确实减慢了一点,但它使代码更加简洁。

以下列课程为例:

class Ex1:
    def __init__(self, v):
        self.v = v
    def __add__(self, other):
        # Many lines of essential code
        return self.v + other.v
    def __sub__(self, other):
        # Many lines of essential code
        return self.v - other.v
    def __mul__(self, other):
        # Many lines of essential code
        return self.v * other.v
    def __truediv__(self, other):
        # Many lines of essential code
        return self.v / other.v

import operator as ops

class Ex2:
    def __init__(self, v):
        self.v = v
    def __op__(self, other, op):
        if op == '+':
            op = ops.add
        elif op == '-':
            op = ops.sub
        elif op == '*':
            op = ops.mul
        elif op == '/':
            op = ops.truediv
        # Many lines of essential code
        return op(self.v, other.v)
    def __add__(self, other):
        return self.__op__(other, '+')
    def __sub__(self, other):
        return self.__op__(other, '-')
    def __mul__(self, other):
        return self.__op__(other, '*')
    def __truediv__(self, other):
        return self.__op__(other, '/')

使用timeit模块测试它我得到了这个:

>>> timeit('Ex1(352) + Ex1(139)', 'from __main__ import Ex1')
1.2401711247332514
>>> timeit('Ex1(352) + Ex1(139)', 'from __main__ import Ex1')
1.2278626568422624
>>> timeit('Ex1(352) + Ex1(139)', 'from __main__ import Ex1')
1.2270929157546107
>>>
>>> timeit('Ex2(352) + Ex2(139)', 'from __main__ import Ex2')
1.6781722774976515
>>> timeit('Ex2(352) + Ex2(139)', 'from __main__ import Ex2')
1.6906975044787487
>>> timeit('Ex2(352) + Ex2(139)', 'from __main__ import Ex2')
1.678191572340893

所以Ex21.36慢约Ex1倍。但是在某些(罕见的)情况下如果使用Ex2的“解决方法”,就可以消除数百行代码。但总的来说,速度是否会因消除线路而受到重视?专业人员是否愿意牺牲一点速度来消除冗余的代码行?

修改

我意识到我可以通过用实际函数(例如ops.add)替换op参数(来自符号;例如'+')来消除if语句。

0 个答案:

没有答案