Traversing through objects.


ABSTRACT: I analyse how much time it takes to change one variable in numerous objects for three languages: C++, Python and Octave.
C++ is of course the fastest, Octave is shamefully slow.

CODE REPOSITORY: On Github

LINUX MACHINE: Linux examples presented in this post were run on Asus G752VY (mid-2016) laptop with Gentoo Linux (kernel: 4.9.16 Gentoo flavour).


Why am I writing this post?
Once I was doing some custom simulations on my laptop. The simulation script was written in Python 3 and it extensively used object-oriented programming.
The simulation took way longer than I expected, so I started to profile the code looking for a bottleneck…


The results of profiling were surprising: going through a list with objects and tweaking a single value in every object takes a lot of time.


What is going on in the experiment?
This experiment is prepared in three versions: for Python 3, Octave and C++.


For all these languages the experiment looks similar: I generate a number of objects (100 to 1 million), and store them in a list (Python), cell array (Octave), or keep a table with pointers to the objects (C++).


The objects are instantiations of a simple class (called `SC`), which consists of one variable: `val`. Definition of `SC` for Python:

class SC():
    """
    `SC` - Simple Class definition.
     
        This is a definition of a class
        with one class variable `val`.
    """

    def __init__(self, val_):
        self.val = val_


Then I measure time needed to change (increment) `val` variable in every object. For Python the time measurement looks as follows:

    # Register traverse through objects
    iRegoTr = csw.reg_code(' %d objects' % iN)

    # Generate the required number of objects
    lObj = generate_objects(iN)

    # Traverse through all the objects
    csw.call_start(iRegoTr)
    traverse_objects(lObj, iN)
    csw.call_stop(iRegoTr)

def traverse_objects(lObj, iN):

    # Loop over all the objects
    for i in range(iN):
        lObj[i].val = lObj[i].val + 1;


The experiment uses Cosniwa software. Cosniwa is a multi-language tool for code profiling.


Results.
The results are shown below.

Time of traversing through objects


Time was measured for different number of objects. C++ was obviously the fastest, with acceptable results. Python is significantly slower, ca. 40 – 50 times slower than C++. Octave is extremely slow in traversing through objects.

Conclusions.
Traversing through many objects is time-expensive in both Python and Octave. If you need speed performance avoid multi-object code in these languages.


In the above case it would be a way better idea to create a vector which contains variables `val` for every object.

Copyright © 2019 | First Mag designed by Themes4WP