Reducing function overheads in python

I developed an application that simulates N robots moving in a grid that try to maximize the number of visited grid cells in a limited number of steps that occur at a target point. Everything is working correctly, but terribly slow. This is currently python + numpy + mathplotlib.

Maximum robots can have a soft limit of 100 (if it can get higher, it's nice to have).

To do this, I do the following, simplified:

while steps > 0:
    for robot in robots:
        agent.calc(robot,steps)

A robot is an array of 1x2 numpy (x-and-y-coordinates).

The agent here decides what to do. Since I need to switch tactics and strategy on the fly, I cannot move this logic.

agent.calc updates the robot in place, one by one.

cProfiling returns. Top extraction

         39014272 function calls (39010490 primitive calls) in 150.314 seconds

   Ordered by: internal time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
 12417735   62.807    0.000   62.807    0.000 distance.py:8(taxicab_distance)
   124596   36.882    0.000   36.882    0.000 {numpy.core.multiarray.array}
   113657   30.204    0.000  100.800    0.001 logical_agent.py:16(choose_max_distance_to...)
 12417013    6.579    0.000   69.384    0.000 squaregrid.py:30(distance)
   113700    2.900    0.000  109.769    0.001 logical_agent.py:73(calc)
 11652363    2.625    0.000    2.625    0.000 {method 'append' of 'list' objects}
   161849    1.653    0.000    1.653    0.000 distance.py:11(euclidean_distance)
   113664    1.632    0.000    1.632    0.000 {sorted}
   114834    1.185    0.000    1.185    0.000 {method 'keys' of 'dict' objects}
   113700    0.695    0.000    1.134    0.000 squaregrid.py:19(neighbours)

, squaregird. , , Manhattan/taxicab euclidean. distance.py, .

, taxicab_distance alot, , , .

,

def taxicab_distance(u, v):
    return np.abs(u[0] - v[0]) + np.abs(u[1] - v[1])

, python , , . {Numpy.core.multiarray.array} , , , .

: β†’ environment.distance β†’ taxicab_distance

, , ? pythons c extensibility, cython, . ? , ?

+4
2

inlining, ~ 15 . crunching ++ cython . 1 .

EDIT: cpython β†’ cython

+2

:

def taxicab_distance(u, v):
     return np.sum(np.abs(u - v))

taxicab_distance ?

+4

All Articles