Last active
January 10, 2021 15:59
-
-
Save thomwolf/c714cda61e67e6723b5e3b5d3b5f0d70 to your computer and use it in GitHub Desktop.
A Cython loop on an array of C structs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from cymem.cymem cimport Pool | |
from random import random | |
cdef struct Rectangle: | |
float w | |
float h | |
cdef int check_rectangles(Rectangle* rectangles, int n_rectangles, float threshold): | |
cdef int n_out = 0 | |
# C arrays contain no size information => we need to give it explicitly | |
for rectangle in rectangles[:n_rectangles]: | |
if rectangle[i].w * rectangle[i].h > threshold: | |
n_out += 1 | |
return n_out | |
def main(): | |
cdef: | |
int n_rectangles = 10000000 | |
float threshold = 0.25 | |
Pool mem = Pool() | |
Rectangle* rectangles = <Rectangle*>mem.alloc(n_rectangles, sizeof(Rectangle)) | |
for i in range(n_rectangles): | |
rectangles[i].w = random() | |
rectangles[i].h = random() | |
n_out = check_rectangles(rectangles, n_rectangles, threshold) | |
print(n_out) |
This informed me about the module cymem as well. Neat little tool.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very cool, didn't know about cymen before now. Awesome!