paulross / notesoncython Goto Github PK
View Code? Open in Web Editor NEWSome notes on using Cython to increase the performance of Python code.
Some notes on using Cython to increase the performance of Python code.
There are lots of ways to write Cython. I normally suggest writing the optimised function with a pure C interface, declared "nogil". The nogil declaration tells the Cython compiler there can be no Python objects within the function body. This gives you much better compiler errors, because the compiler doesn't have to guess that something could be Python trickery. Writing this way gives quite nice code:
# cython: infer_types=True
cdef double std_dev(const double arr*, size_t size) nogil:
cdef double mean = 0.0
for pval in arr[:size]:
mean += pval
mean /= size
cdef double sum_sq = 0.
for pval in arr[:size]:
sum_sq += (pval-mean)**2
return (sum_sq / size)**0.5
The only weird syntax is the for pval in arr[:size]
loop. You could just as easily do:
for i in range(size):
pval = arr[i]
But looping over the value is pretty convenient.
Incidentally working with Cython nogil functions can give nicer code than the equivalent Python. The reason is that in Python, we become so scared of the function call overhead that we're reluctant to break things up. In Cython and C this isn't true -- so we might prefer the following:
# cython: infer_types=True
cdef double std_dev(const double arr*, size_t size) nogil:
mean = get_mean(arr, size)
cdef double sum_sq = 0.
for pval in arr[:size]:
sum_sq += (pval-mean)**2
return (sum_sq / size)**0.5
cdef double get_mean(const double arr*, size_t size) nogil:
cdef double mean = 0.0
for pval in arr[:size]:
mean += pval
return mean / size
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.