I try to define my numba object to accelerate my codes with jitclass
Here is my definitions of the object
from numba import float64
from numba.experimental import jitclass
import numpy as np
from shapely.geometry import Polygon as ShapelyPolygon
from shapely.geometry import Point
import time
import os
@jitclass([('vertices', float64[:, :])])
class NumbaPolygon:
def __init__(self, vertices):
self.vertices = vertices
def contains_point(self, point):
"""To check if the point is inside the polygon"""
x, y = point
inside = False
x_vertices = self.vertices[:, 0]
y_vertices = self.vertices[:, 1]
n = self.vertices.shape[0]
p1x, p1y = x_vertices[0], y_vertices[0]
for i in range(n + 1):
p2x, p2y = x_vertices[i % n], y_vertices[i % n]
if y > min(p1y, p2y):
if y <= max(p1y, p2y):
if x <= max(p1x, p2x):
if p1y != p2y:
xinters = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x
if p1x == p2x or x <= xinters:
inside = not inside
p1x, p1y = p2x, p2y
return inside
Then, I use the following codes to do the benchmark of the first compilation of the object
vertices = np.array([[0, 0], [10, 0], [10, 10], [0, 10]], dtype=np.float64)
point = np.array([0.5,0.5], dtype=np.float64)
t1 = time.perf_counter_ns()
numba_poly = NumbaPolygon(vertices)
numba_poly.contains_point(point)
consuming_time = time.perf_counter_ns() - t1
print(f'JITCLASS method takes {consuming_time/1e6:.6f} ms')
t1 = time.perf_counter_ns()
poly = ShapelyPolygon(vertices)
poly.contains(Point(*point))
consuming_time = time.perf_counter_ns() - t1
print(f'Shapely method takes {consuming_time/1e6:.6f} ms')
Here is the results:
JITCLASS method takes 436.783740 ms
Shapely method takes 0.288628 ms
Though the second-try really takes less time, it is hard to compensate the required initialization time.
Second Try:
JITCLASS method takes 0.064460 ms
Shapely method takes 0.511835 ms
Hence, as title, I want to find any method to accelerate the initialization of the object.
Thanks in advanced!