Optimizing the speed of data access using foreach_()

The Python language used in the Blender API is very loyal and undemanding when it comes to data typing. However, when working with large amounts of data, the universalization of type conversion can negatively affect the speed of the code. For example, the simplest foreach_get() cycle, which takes data from a set of elements and puts it into an array, can be significantly speeded up simply by choosing the right type of the destination array data.

User Mysteryem in the Blender chat conducted a study on the example of getting data for the location of each particle in a particle system of 10,000 elements.

In his experiment, different types of arrays were created, into which the location of particles was placed using the foreach_get() instruction.

Arrays were created of the following types:

  • regular array of floating point numbers (float)
  • regular array of double precision floating point numbers (double)
  • numpy array of floating point numbers (float)
  • numpy array of double precision floating point numbers (double)
  • ctypes array of floating point numbers (float)
  • ctypes array of double precision floating point numbers d(ouble)

Mysteryem’s code:

The result of executing the code is as follows:

Execution results may depend on the computer and operating system you are using.

Based on the results of executing the code, the following conclusions can be drawn:

Numpy array is the best.

The maximum speed was demonstrated by the foreach_get() loop when using a numpy array with a float data type, which corresponds to the particle location data type.

Any difference with the original data type requires additional conversions, which can significantly affect the speed of the loop. So, the same numpy array shows a significant decrease in speed when using the double type.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments