下面的类是纯python,但是在密集计算上有点慢,导致大约1分钟完成大约500万个动作。
问题:
- 有没有办法用 C 语言编写它们并将它们导入 python 以提高速度?
- 如何?
用法是这样的:
_cm=Unit(...) # Unit
_m =Unit(...) # Unit
a= 1*_cm # UnitValue
b= 2*_m # UnitValue
_m2 = _m**2 # Unit
b*a == 0.02 * _m2 # UnitValue
a*b == 200 * _cm2 # UnitValue # _cm2 is auto created unit based on Unit.__new__
b-a = 0.99*_m # UnitValue
a-b = -99*_cm # UnitValue
# and so on...
注意:课程比这里包含的要大...
class Unit(object):
def __new__(self, *args, **kwargs):
# check if this unit not created before and if ues return before created-one.
# useful for cmp between units.
return created_or_new_unit_instance
def __div__(self, other):
return self * (other ** -1) # self / other
def __rdiv__(self, other):
return other * (self ** -1) # other / self
def __rmul__(self, other):
return self * other # other * self
def __mul__(self, other): # self * other
if isinstance(other, SUPPORTED_NUMBERS):
return UnitValue(other, self)
elif isinstance(other, UnitValue): # FIXME DOUBLICATED!
return (other.value * (other.unit * self))
elif isinstance(other, Unit): # multipling two units self * other
# calculate the other exchange factor againest self in `v`
if v == 1.0:
# the bases may differ from self.bases or other.bases
# so just create a new Unit and let __new__ handle doublication.
return Unit(bases)
else:
return v * Unit(bases)
return NotImplemented
def __pow__(self, other, modulo=None): # @UnusedVariable
# create new powered unit.
return new Unit
和另一个类:
class UnitValue(object):
def __init__(self, value, unit):
self.value = value
self.unit = unit
def __add__(self, other): # self + other
if isinstance(other, UnitValue):
o = self.unit.get_unitvalue_in_this_unit(other) # other is UnitValue
v = self.value + o.value
return UnitValue(v, self.unit)
if other == 0:
return UnitValue(self.value, self.unit)
return NotImplemented
def __mul__(self, other): # self * other
if isinstance(other, SUPPORTED_NUMBERS):
return UnitValue(other * self.value, self.unit)
elif isinstance(other, UnitValue):
return (self.value * other.value) * (self.unit * other.unit)
return NotImplemented
def __pow__(self, other, modulo=None):
v = self.value ** other
u = self.unit ** other
if modulo:
v = v % modulo
return UnitValue(v, u)
def __cmp__(self, other):
if isinstance(other, UnitValue):
vo = self.unit.get_unitvalue_in_this_unit(other).value
else:
vo = other
if vo is None:
vo = 0
diff = self.value - vo
epsi = 1e-10
if abs(diff) < epsi: return 0
elif diff > 0: return 1
elif diff < 0: return -1