The Beauty and the Beast

A Python, Cython, and C++ cheatsheet


Simple and reliable timing within a script

Use in a loop to calculate the average or median of elapsed times:

from timeit import default_timer

t0 = default_timer()
# Code to be timed
cy_elapsed = default_timer() - t0

Basic plotting

import numpy as np
import matplotlib.pyplot as plt

# Create the x-range
x_min = 0.0
x_max = 1.0
x_step = 0.001
x = np.arange(x_min, x_max + x_step, x_step)

# A test function as a lambda stored in a dictionary
tests = {1: lambda x, beta = 2.0: -x / (x * x + beta)}

plt.plot(x, tests[1](x))


Use of the C++ STL in Cython

# distutils: language = c++
# distutils: extra_compile_args = ['-std=c++11', '-stdlib=libc++']
# Compiler directives have to be comments at the top of the file,
# therefore this comment has to follow the directives.

# For additional speed gain, bound checking and negative indices can
# be disabled.
from cython cimport boundscheck, wraparound

# Import the C++ vector.
# C++
from libcpp.vector cimport vector

# Declare the std::fill
cdef extern from "" namespace "std":
    void std_fill "std::fill" [iter](iter first,
                                     iter last,
                                     double value)

# Import a C function.
# C
from libc.math cimport pow


Plot inline.

import matplotlib.pyplot as plt
%matplotlib inline

# Set the size for all figures. [6.0, 4.0] is the default size.
plt.rcParams['figure.figsize'] = [6.0, 4.0]


Under construction

This entry was posted in . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s