vector3dPerfΒΆ

Performance check of Vector3d [] access.

setup 0. Direct access is by accessing .x .y or .z setup 1. ifel is an algorithm using if-elif statement. setup 2. set is instance set and access by index.

0 is obviously the fastest. Comparing 1 and 2, 1 is faster by ~10% on average. Comparing 0 and 1, 0 is double by a factor of 2.

''' Performance check of Vector3d [] access.

setup 0. Direct access is by accessing .x .y or .z
setup 1. ifel is an algorithm using if-elif statement.
setup 2. set is instance set and access by index.

0 is obviously the fastest.
Comparing 1 and 2, 1 is faster by ~10% on average.
Comparing 0 and 1, 0 is double by a factor of 2.

'''

import numpy

defclass = '''
import random 

class V:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

class V1(V):
    def __getitem__(self, idx):
        if idx == 0:
            return self.x
        elif idx == 1:
            return self.y
        elif idx == 2:
            return self.z
        else:
            raise IndexError()

class V2(V):
    def __getitem__(self, idx):
        return (self.x, self.y, self.z)[idx]
'''


import timeit

setup0 = ''' %s

def getting():
    v = V1(random.random(), random.random(), random.random())
    vv = (v.x, v.y, v.z)
''' % defclass

setup1 = ''' %s

def getting():
    v = V1(random.random(), random.random(), random.random())
    vv = (v[0], v[1], v[2])
''' % defclass
setup2 = ''' %s

def getting():
    v = V2(random.random(), random.random(), random.random())
    vv = (v[0], v[1], v[2])
''' % defclass

def main():

    t = timeit.Timer('getting()', setup0)
    res0 = numpy.array(t.repeat(20, 10000))

    print("Direct access:")
    print(res0)
    print('*'*70)

    t = timeit.Timer('getting()', setup1)
    res1 = numpy.array(t.repeat(20, 10000))

    print("If-elif statement access:")
    print(res1)
    print('*'*70)

    t = timeit.Timer('getting()', setup2)
    res2 = numpy.array(t.repeat(20, 10000))

    print("Set instance:")
    print(res2)
    print('*'*70)

    print("Direct: max=%.4f min=%.4f ave=%.4f med=%.4f" % (res0.max(), res0.min(), numpy.average(res0), numpy.median(res0)))
    print("ifel  : max=%.4f min=%.4f ave=%.4f med=%.4f" % (res1.max(), res1.min(), numpy.average(res1), numpy.median(res1)))
    print("set   : max=%.4f min=%.4f ave=%.4f med=%.4f" % (res2.max(), res2.min(), numpy.average(res2), numpy.median(res2)))

if __name__ == '__main__':
    main()