Skip to content

Instantly share code, notes, and snippets.

@thomwolf
Last active January 10, 2021 15:59
Show Gist options
  • Save thomwolf/c714cda61e67e6723b5e3b5d3b5f0d70 to your computer and use it in GitHub Desktop.
Save thomwolf/c714cda61e67e6723b5e3b5d3b5f0d70 to your computer and use it in GitHub Desktop.
A Cython loop on an array of C structs
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)
@runekaagaard
Copy link

Very cool, didn't know about cymen before now. Awesome!

@PiepsC
Copy link

PiepsC commented Dec 1, 2019

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