Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update fractal_ctypes.py #5

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions fractal_ctypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,29 +13,34 @@ class CtypesImg(ctypes.Structure):
('height', ctypes.c_int),
('data', ctypes.POINTER(ctypes.c_uint8)), # HUH?
]

array_cache = {}

def __init__(self, width, height):
self.width = width
self.height = height
# Create a class type to hold the data.
# Since this creates a type, cache it for reuse rather
# than create a new one each time

if width*height not in self.array_cache:
self.array_cache[width*height] = ctypes.c_uint8 * (width * height)

# Note this keeps the img.data alive in the interpreter
self.data = self.array_cache[width*height]() # !!!!!!

def asmemoryview(self):
# There must be a better way, but this code will not
# be timed, so explicit trumps implicit
ret = self.array_cache[width*height]()

for i in range(width*height):
ret[i] = self.data[i]

return ret

ctypesimg = CtypesImg(width, height)


# Load the DLL
cdll = ctypes.cdll.LoadLibrary('./libcreate_fractal.so')

Expand All @@ -47,16 +52,17 @@ def asmemoryview(self):
mandel_ctypes.argtypes = [ctypes.c_float, ctypes.c_float, ctypes.c_int,
ctypes.POINTER(ctypes.c_uint8)]


if __name__ == "__main__":
from timeit import default_timer as timer
from PIL import Image
from create_fractal import create_fractal

s = timer()
create_fractal_ctypes(ctypesimg, 20)
e = timer()
ctypes_onecall = e - s
print('ctypes calling create_fractal required {:.2f} millisecs'.format(1000*ctypes_onecall))

print(f'ctypes calling create_fractal required {1000 * ctypes_onecall} millisecs')
data = ctypesimg.asmemoryview()
print(max(data))
im = Image.frombuffer("L", (width, height), data, 'raw', 'L', 0, 1)
Expand All @@ -68,7 +74,9 @@ def asmemoryview(self):
e = timer()
ctypes_createfractal = e - s
data = ctypesimg.asmemoryview()

print(max(data))
print('ctypes calling mandel required {:.2f} millisecs'.format(1000*ctypes_createfractal))
print(f'ctypes calling mandel required {1000 * ctypes_createfractal} millisecs')

im = Image.frombuffer("L", (width, height), data, 'raw', 'L', 0, 1)
im.save('ctypes_mandel.png')