0% found this document useful (0 votes)
14 views

Python High Performance Programming Boost the performance of your Python programs using advanced techniques 1st Edition Gabriele Lanaro download

The document provides information about the book 'Python High Performance Programming' by Gabriele Lanaro, which focuses on enhancing Python program performance using advanced techniques. It covers topics such as benchmarking, profiling, fast array operations with NumPy, C performance with Cython, and parallel processing. The book is aimed at intermediate to advanced Python programmers, particularly those in scientific fields, and includes practical examples and tools for optimization.

Uploaded by

rhuleannasvt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Python High Performance Programming Boost the performance of your Python programs using advanced techniques 1st Edition Gabriele Lanaro download

The document provides information about the book 'Python High Performance Programming' by Gabriele Lanaro, which focuses on enhancing Python program performance using advanced techniques. It covers topics such as benchmarking, profiling, fast array operations with NumPy, C performance with Cython, and parallel processing. The book is aimed at intermediate to advanced Python programmers, particularly those in scientific fields, and includes practical examples and tools for optimization.

Uploaded by

rhuleannasvt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

Python High Performance Programming Boost the

performance of your Python programs using


advanced techniques 1st Edition Gabriele Lanaro
pdf download
https://ebookname.com/product/python-high-performance-
programming-boost-the-performance-of-your-python-programs-using-
advanced-techniques-1st-edition-gabriele-lanaro/

Get Instant Ebook Downloads – Browse at https://ebookname.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Python High Performance 2nd Edition Gabriele Lanaro

https://ebookname.com/product/python-high-performance-2nd-
edition-gabriele-lanaro/

Fundamentals of Python First Programs 1st Edition


Kenneth A. Lambert

https://ebookname.com/product/fundamentals-of-python-first-
programs-1st-edition-kenneth-a-lambert/

Beginning Python Using Python 2 6 and Python 3 1 Wrox


Programmer to Programmer James Payne

https://ebookname.com/product/beginning-python-using-
python-2-6-and-python-3-1-wrox-programmer-to-programmer-james-
payne/

Religion and Politics in the Middle East Identity


Ideology Institutions and Attitudes Second Edition,
Edition Robert D. Lee

https://ebookname.com/product/religion-and-politics-in-the-
middle-east-identity-ideology-institutions-and-attitudes-second-
edition-edition-robert-d-lee/
Gilbert Law Summary on Criminal Procedure 19th ed.
Edition Paul Marcus

https://ebookname.com/product/gilbert-law-summary-on-criminal-
procedure-19th-ed-edition-paul-marcus/

Dream Lucky When FDR was in the White House Count Basie
was on the radio and everyone wore a hat 1st Edition
Roxane Orgill

https://ebookname.com/product/dream-lucky-when-fdr-was-in-the-
white-house-count-basie-was-on-the-radio-and-everyone-wore-a-
hat-1st-edition-roxane-orgill/

Making sense of the dollar exposing dangerous myths


about trade and foreign exchange 1st Edition Chandler

https://ebookname.com/product/making-sense-of-the-dollar-
exposing-dangerous-myths-about-trade-and-foreign-exchange-1st-
edition-chandler/

Constitutional and Administrative Law Helen Fenwick

https://ebookname.com/product/constitutional-and-administrative-
law-helen-fenwick/

The Syriac Bible According to the Mosul Edition Y■suf


D■w■d

https://ebookname.com/product/the-syriac-bible-according-to-the-
mosul-edition-yusuf-dawud/
The Bible in the Syriac Tradition Third Edition
Sebastian Brock

https://ebookname.com/product/the-bible-in-the-syriac-tradition-
third-edition-sebastian-brock/
Python High Performance
Programming

Boost the performance of your Python programs


using advanced techniques

Gabriele Lanaro

BIRMINGHAM - MUMBAI
Python High Performance Programming

Copyright © 2013 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embedded in
critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy
of the information presented. However, the information contained in this book is
sold without warranty, either express or implied. Neither the author, nor Packt
Publishing, and its dealers and distributors will be held liable for any damages
caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.

First published: December 2013

Production Reference: 1171213

Published by Packt Publishing Ltd.


Livery Place
35 Livery Street
Birmingham B3 2PB, UK.

ISBN 978-1-78328-845-8

www.packtpub.com

Cover Image by Gagandeep Sharma (er.gagansharma@gmail.com)


Credits

Author Project Coordinator


Gabriele Lanaro Sherin Padayatty

Reviewers Proofreader
Daniel Arbuckle Linda Morris
Mike Driscoll
Albert Lukaszewski Indexer
Rekha Nair

Acquisition Editors
Owen Roberts Production Coordinators
Pooja Chiplunkar
Harsha Bharwani
Manu Joseph

Commissioning Editor
Shaon Basu Cover Work
Pooja Chiplunkar

Technical Editors
Akashdeep Kundu
Faisal Siddiqui
About the Author

Gabriele Lanaro is a PhD student in Chemistry at the University of British


Columbia, in the field of Molecular Simulation. He writes high performance
Python code to analyze chemical systems in large-scale simulations. He is the
creator of Chemlab—a high performance visualization software in Python—and
emacs-for-python—a collection of emacs extensions that facilitate working with
Python code in the emacs text editor. This book builds on his experience in
writing scientific Python code for his research and personal projects.

I want to thank my parents for their huge, unconditional love and


support. My gratitude cannot be expressed by words but I hope
that I made them proud of me with this project.

I would also thank the Python community for producing and


maintaining a massive quantity of high-quality resources made
available for free. Their extraordinary supportive and compassionate
attitude really fed my passion for this amazing technology.

A special thanks goes to Hessam Mehr for reviewing my drafts,


testing the code and providing extremely valuable feedback. I would
also like to thank my roommate Kaveh for being such an awesome
friend and Na for bringing me chocolate bars during rough times.
About the Reviewers

Dr. Daniel Arbuckle is a published researcher in the fields of robotics and


nanotechnology, as well as a professional Python programmer. He is the author
of Python Testing: Beginner's Guide from Packt Publishing and one of the authors
of Morphogenetic Engineering from Springer-Verlag.

Mike Driscoll has been programming in Python since Spring 2006. He enjoys
writing about Python on his blog at http://www.blog.pythonlibrary.org/.
Mike also occasionally writes for the Python Software Foundation, i-Programmer,
and Developer Zone. He enjoys photography and reading a good book. Mike has
also been a technical reviewer for Python 3 Object Oriented Programming, Python
2.6 Graphics Cookbook, and Tkinter GUI Application Development Hotshot.

I would like to thank my beautiful wife, Evangeline, for always


supporting me. I would also like to thank friends and family for
all that they do to help me. And I would like to thank Jesus Christ
for saving me.

Albert Lukaszewski is a software consultant and the author of MySQL for


Python. He has programmed computers for nearly 30 years. He specializes in
high-performance Python implementations of network and database services.
He has designed and developed Python solutions for a wide array of industries
including media, mobile, publishing, and cinema. He lives with his family in
southeast Scotland.
www.PacktPub.com

Support files, eBooks, discount offers and more


You might want to visit www.PacktPub.com for support files and downloads related
to your book.

Did you know that Packt offers eBook versions of every book published, with PDF
and ePub files available? You can upgrade to the eBook version at www.PacktPub.
com and as a print book customer, you are entitled to a discount on the eBook copy.
Get in touch with us at service@packtpub.com for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign
up for a range of free newsletters and receive exclusive discounts and offers on Packt
books and eBooks.
TM

http://PacktLib.PacktPub.com

Do you need instant solutions to your IT questions? PacktLib is Packt's online


digital book library. Here, you can access, read and search across Packt's entire
library of books.

Why Subscribe?
• Fully searchable across every book published by Packt
• Copy and paste, print and bookmark content
• On demand and accessible via web browser

Free Access for Packt account holders


If you have an account with Packt at www.PacktPub.com, you can use this to access
PacktLib today and view nine entirely free books. Simply use your login credentials
for immediate access.
Table of Contents
Preface 1
Chapter 1: Benchmarking and Profiling 7
Designing your application 7
Writing tests and benchmarks 13
Timing your benchmark 15
Finding bottlenecks with cProfile 17
Profile line by line with line_profiler 21
Optimizing our code 23
The dis module 25
Profiling memory usage with memory_profiler 26
Performance tuning tips for pure Python code 28
Summary 30
Chapter 2: Fast Array Operations with NumPy 31
Getting started with NumPy 31
Creating arrays 32
Accessing arrays 34
Broadcasting 37
Mathematical operations 40
Calculating the Norm 41
Rewriting the particle simulator in NumPy 41
Reaching optimal performance with numexpr 45
Summary 47
Table of Contents

Chapter 3: C Performance with Cython 49


Compiling Cython extensions 49
Adding static types 52
Variables 52
Functions 54
Classes 55
Sharing declarations 56
Working with arrays 58
C arrays and pointers 58
NumPy arrays 60
Typed memoryviews 61
Particle simulator in Cython 63
Profiling Cython 67
Summary 70
Chapter 4: Parallel Processing 71
Introduction to parallel programming 72
The multiprocessing module 74
The Process and Pool classes 74
Monte Carlo approximation of pi 77
Synchronization and locks 80
IPython parallel 82
Direct interface 83
Task-based interface 87
Parallel Cython with OpenMP 88
Summary 91
Index 93

[ ii ]
Preface
Python is a programming language renowned for its simplicity, elegance, and
the support of an outstanding community. Thanks to the impressive amount
of high-quality third-party libraries, Python is used in many domains.

Low-level languages such as C, C++, and Fortran are usually preferred in


performance-critical applications. Programs written in those languages
perform extremely well, but are hard to write and maintain.

Python is an easier language to deal with and it can be used to quickly write
complex applications. Thanks to its tight integration with C, Python is able to
avoid the performance drop associated with dynamic languages. You can use
blazing fast C extensions for performance-critical code and retain all the
convenience of Python for the rest of your application.

In this book, you will learn, in a step-by-step method how to find and speedup
the slow parts of your programs using basic and advanced techniques.

The style of the book is practical; every concept is explained and illustrated with
examples. This book also addresses common mistakes and teaches how to avoid
them. The tools used in this book are quite popular and battle-tested; you can be
sure that they will stay relevant and well-supported in the future.

This book starts from the basics and builds on them, therefore, I suggest you
to move through the chapters in order.

And don't forget to have fun!


Preface

What this book covers


Chapter 1, Benchmarking and Profiling shows you how to find the parts of your
program that need optimization. We will use tools for different use cases and
explain how to analyze and interpret profiling statistics.

Chapter 2, Fast Array Operations with NumPy is a guide to the NumPy package.
NumPy is a framework for array calculations in Python. It comes with a clean
and concise API, and efficient array operations.

Chapter 3, C Performance with Cython is a tutorial on Cython: a language that acts


as a bridge between Python and C. Cython can be used to write code using a
superset of the Python syntax and to compile it to obtain efficient C extensions.

Chapter 4, Parallel Processing is an introduction to parallel programming. In


this chapter, you will learn how parallel programming is different from serial
programming and how to parallelize simple problems. We will also explain
how to use multiprocessing, IPython.parallel and cython.parallel to
write code for multiple cores.

What you need for this book


This book requires a Python installation. The examples work for both Python 2.7
and Python 3.3 unless indicated otherwise.

In this book, we will make use of some popular Python packages:

• NumPy (Version 1.7.1 or later): This package is downloadable from the


official website (http://www.scipy.org/scipylib/download.html)
and available in most of the Linux distributions
• Cython (Version 0.19.1 or later): Installation instructions are present in the
official website (http://docs.cython.org/src/quickstart/install.
html); notice that you also need a C compiler, such as GCC (GNU Compiler
Collection), to compile your C extensions
• IPython (Version 0.13.2 or later): Installation instructions are present in the
official website (http://ipython.org/install.html)

The book was written and tested on Ubuntu 13.10. The examples will likely run on
Mac OS X with little or no changes.

My suggestion for Windows users is to install the Anaconda Python distribution


(https://store.continuum.io/cshop/anaconda/), which comes with a complete
environment suitable for scientific programming.

[2]
Preface

A convenient alternative is to use the free service wakari.io: a cloud-based Linux


and Python environment that includes the required packages with their tools and
utilities. No setup is required.

In Chapter 1, Benchmarking and Profiling, we will use KCachegrind (http://


sourceforge.net/projects/kcachegrind/), which is available for Linux.
KCachegrind has also a port for Windows—QcacheGrind—which is also installable
from source on Mac OS X.

Who this book is for


This book is for intermediate to advanced Python programmers who develop
performance-critical applications. As most of the examples are taken from scientific
applications, the book is a perfect match for scientists and engineers looking to
speed up their numerical codes.

However, the scope of this book is broad and the concepts can be applied to any
domain. Since the book addresses both basic and advanced topics, it contains
useful information for programmers with different Python proficiency levels.

Conventions
In this book, you will find a number of styles of text that distinguish between
different kinds of information. Here are some examples of these styles, and an
explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions,
pathnames, dummy URLs, user input, and Twitter handles are shown as follows:
"The plot function included in matplotlib can display our particles as points
on a Cartesian grid and the FuncAnimation class can animate the evolution of
our particles over time."

A block of code is set as follows:


from matplotlib import pyplot as plt
from matplotlib import animation

def visualize(simulator):

X = [p.x for p in simulator.particles]


Y = [p.y for p in simulator.particles]

[3]
Preface

When we wish to draw your attention to a particular part of a code block, the
relevant lines or items are set in bold:
In [1]: import purepy
In [2]: %timeit purepy.loop()
100 loops, best of 3: 8.26 ms per loop
In [3]: %timeit purepy.comprehension()
100 loops, best of 3: 5.39 ms per loop
In [4]: %timeit purepy.generator()
100 loops, best of 3: 5.07 ms per loop

Any command-line input or output is written as follows:


$ time python simul.py # Performance Tuned
real 0m0.756s
user 0m0.714s
sys 0m0.036s

New terms and important words are shown in bold. Words that you see on the
screen, in menus or dialog boxes, for example, appear in the text like this: "You
can navigate to the Call Graph or the Caller Map tabs by double-clicking on the
rectangles."

Warnings or important notes appear in a box like this.

Tips and tricks appear like this.

Reader feedback
Feedback from our readers is always welcome. Let us know what you think about
this book—what you liked or may have disliked. Reader feedback is important for
us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to feedback@packtpub.com,


and mention the book title via the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing
or contributing to a book, see our author guide on www.packtpub.com/authors.

[4]
Preface

Customer support
Now that you are the proud owner of a Packt book, we have a number of things to
help you to get the most from your purchase.

Downloading the example code


You can download the example code files for all Packt books you have purchased
from your account at http://www.packtpub.com. If you purchased this book
elsewhere, you can visit http://www.packtpub.com/support and register to
have the files e-mailed directly to you.

Errata
Although we have taken every care to ensure the accuracy of our content, mistakes
do happen. If you find a mistake in one of our books—maybe a mistake in the text or
the code—we would be grateful if you would report this to us. By doing so, you can
save other readers from frustration and help us improve subsequent versions of this
book. If you find any errata, please report them by visiting http://www.packtpub.
com/submit-errata, selecting your book, clicking on the errata submission form link,
and entering the details of your errata. Once your errata are verified, your submission
will be accepted and the errata will be uploaded on our website, or added to any list of
existing errata, under the Errata section of that title. Any existing errata can be viewed
by selecting your title from http://www.packtpub.com/support.

Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media.
At Packt, we take the protection of our copyright and licenses very seriously. If you
come across any illegal copies of our works, in any form, on the Internet, please
provide us with the location address or website name immediately so that we can
pursue a remedy.

Please contact us at copyright@packtpub.com with a link to the suspected


pirated material.

We appreciate your help in protecting our authors, and our ability to bring you
valuable content.

Questions
You can contact us at questions@packtpub.com if you are having a problem with
any aspect of the book, and we will do our best to address it.

[5]
Benchmarking and Profiling
Recognizing the slow parts of your program is the single most important task when it
comes to speeding up your code. In most cases, the bottlenecks account for a very small
fraction of the program. By specifically addressing those critical spots you can focus on
the parts that need improvement without wasting time in micro-optimizations.

Profiling is the technique that allows us to pinpoint the bottlenecks. A profiler


is a program that runs the code and observes how long each function takes to
run, detecting the slow parts of the program. Python provides several tools to
help us find those bottlenecks and navigate the performance metrics. In this
chapter, we will learn how to use the standard cProfile module, line_profiler
and memory_profiler. We will also learn how to interpret the profiling results
using the program KCachegrind.

You may also want to assess the total execution time of your program and see how
it is affected by your changes. We will learn how to write benchmarks and how to
accurately time your programs.

Designing your application


When you are designing a performance-intensive program, the very first step is to
write your code without having optimization in mind; quoting Donald Knuth:

Premature optimization is the root of all evil.

In the early development stages, the design of the program can change quickly,
requiring you to rewrite and reorganize big chunks of code. By testing different
prototypes without bothering about optimizations, you learn more about your
program, and this will help you make better design decisions.
Benchmarking and Profiling

The mantras that you should remember when optimizing your code, are as follows:

• Make it run: We have to get the software in a working state, and be sure that
it produces the correct results. This phase serves to explore the problem that
we are trying to solve and to spot major design issues in the early stages.
• Make it right: We want to make sure that the design of the program is solid.
Refactoring should be done before attempting any performance optimization.
This really helps separate the application into independent and cohesive
units that are easier to maintain.
• Make it fast: Once our program is working and has a good design we want
to optimize the parts of the program that are not fast enough. We may also
want to optimize memory usage if that constitutes an issue.

In this section we will profile a test application—a particle simulator. The simulator
is a program that takes some particles and evolves them over time according to a
set of laws that we will establish. Those particles can either be abstract entities or
correspond to physical objects. They can be, for example, billiard balls moving on
a table, molecules in gas, stars moving through space, smoke particles, fluids in a
chamber, and so on.

Those simulations are useful in fields such as Physics, Chemistry, and Astronomy,
and the programs used to simulate physical systems are typically performance-
intensive. In order to study realistic systems it's often necessary to simulate the
highest possible number of bodies.

In our first example, we will simulate a system containing particles that constantly
rotate around a central point at various speeds, like the hands of a clock.

The necessary information to run our simulation will be the starting positions of
the particles, the speed, and the rotation direction. From these elements, we have
to calculate the position of the particle in the next instant of time.

[8]
Chapter 1

(vx, vy)

(x, y)

(0, 0)

The basic feature of a circular motion is that the particles always move
perpendicularly to the direction connecting the particle and the center, as shown in
the preceding image. To move the particle we simply change the position by taking a
series of very small steps in the direction of motion, as shown in the following figure:

[9]
Benchmarking and Profiling

We will start by designing the application in an object-oriented way. According to


our requirements, it is natural to have a generic Particle class that simply stores
the particle position (x, y) and its angular speed:
class Particle:
def __init__(self, x, y, ang_speed):
self.x = x
self.y = y
self.ang_speed = ang_speed

Another class, called ParticleSimulator will encapsulate our laws of motion and
will be responsible for changing the positions of the particles over time. The __
init__ method will store a list of Particle instances and the evolve method will
change the particle positions according to our laws.

We want the particles to rotate around the point (x, y), which, here, is equal to (0, 0),
at constant speed. The direction of the particles will always be perpendicular to the
direction from the center (refer to the first figure of this chapter). To find this vector

v=(vx ,vy)
(corresponding to the Python variables v_x and v_y) it is sufficient to use these
formulae:

vx= -y/ x 2+y 2


vy= x/ x 2+y 2

If we let one of our particles move, after a certain time dt, it will follow a circular path,
reaching another position. To let the particle follow that trajectory we have to divide
the time interval dt into very small time steps where the particle moves tangentially
to the circle. The final result, is just an approximation of a circular motion and, in fact,
it's similar to a polygon. The time steps should be very small, otherwise the particle
trajectory will diverge quickly, as shown in the following figure:

[ 10 ]
Chapter 1

In a more schematic way, to calculate the particle position at time dt we have to carry
out the following steps:

1. Calculate the direction of motion: v_x, v_y.


2. Calculate the displacement (d_x, d_y) which is the product of time and speed
and follows the direction of motion.
3. Repeat steps 1 and 2 for enough time steps to cover the total time dt.

The following code shows the full ParticleSimulator implementation:


class ParticleSimulator:

def __init__(self, particles):


self.particles = particles

def evolve(self, dt):


timestep = 0.00001
nsteps = int(dt/timestep)

for i in range(nsteps):
for p in self.particles:

# 1. calculate the direction


norm = (p.x**2 + p.y**2)**0.5
v_x = (-p.y)/norm
v_y = p.x/norm

# 2. calculate the displacement


d_x = timestep * p.ang_speed * v_x
d_y = timestep * p.ang_speed * v_y

p.x += d_x
p.y += d_y
# 3. repeat for all the time steps

[ 11 ]
Benchmarking and Profiling

We can use the matplotlib library to visualize our particles. This library is not
included in the Python standard library. To install it, you can follow the instructions
included in the official documentation at:
http://matplotlib.org/users/installing.html

Alternatively, you can use the Anaconda Python distribution


(https://store.continuum.io/cshop/anaconda/)
that includes matplotlib and most of the other third-party
packages used in this book. Anaconda is free and available for
Linux, Windows, and Mac.

The plot function included in matplotlib can display our particles as points on
a Cartesian grid and the FuncAnimation class can animate the evolution of our
particles over time.

The visualize function accomplishes this by taking the particle simulator and
displaying the trajectory in an animated plot.

The visualize function is structured as follows:

• Setup the axes and display the particles as points using the plot function
• Write an initialization function (init) and an update function
(animate) that changes the x, y coordinates of the data points using the
line.set_data method
• Create a FuncAnimation instance passing the functions and some parameters
• Run the animation with plt.show()

The complete implementation of the visualize function is as follows:


from matplotlib import pyplot as plt
from matplotlib import animation

def visualize(simulator):

X = [p.x for p in simulator.particles]


Y = [p.y for p in simulator.particles]

fig = plt.figure()
ax = plt.subplot(111, aspect='equal')
line, = ax.plot(X, Y, 'ro')

# Axis limits
plt.xlim(-1, 1)
plt.ylim(-1, 1)

[ 12 ]
Chapter 1

# It will be run when the animation starts


def init():
line.set_data([], [])
return line,

def animate(i):
# We let the particle evolve for 0.1 time units
simulator.evolve(0.01)
X = [p.x for p in simulator.particles]
Y = [p.y for p in simulator.particles]

line.set_data(X, Y)
return line,

# Call the animate function each 10 ms


anim = animation.FuncAnimation(fig, animate,
init_func=init, blit=True,# Efficient animation
interval=10)
plt.show()

Finally, we define a small test function—test_visualize—that animates a


system of three particles rotating in different directions. Note that the third particle
completes a round three times faster than the others:
def test_visualize():
particles = [Particle( 0.3, 0.5, +1),
Particle( 0.0, -0.5, -1),
Particle(-0.1, -0.4, +3)]

simulator = ParticleSimulator(particles)
visualize(simulator)

if __name__ == '__main__':
test_visualize()

Writing tests and benchmarks


Now that we have a working simulator, we can start measuring our performance
and tuning-up our code, so that our simulator can handle as many particles
as possible. The first step in this process is to write a test and a benchmark.

We need a test that checks whether the results produced by the simulation are
correct or not. In the optimization process we will rewrite the code to try different
solutions; by doing so we may easily introduce bugs. Maintaining a solid test suite
is essential to avoid wasting time on broken code.

[ 13 ]
Benchmarking and Profiling

Our test will take three particle and let the system evolve for 0.1 time units. We
then compare our results, up to a certain precision, with those from a reference
implementation:
def test():
particles = [Particle( 0.3, 0.5, +1),
Particle( 0.0, -0.5, -1),
Particle(-0.1, -0.4, +3)]

simulator = ParticleSimulator(particles)

simulator.evolve(0.1)

p0, p1, p2 = particles

def fequal(a, b):


return abs(a - b) < 1e-5

assert fequal(p0.x, 0.2102698450356825)


assert fequal(p0.y, 0.5438635787296997)

assert fequal(p1.x, -0.0993347660567358)


assert fequal(p1.y, -0.4900342888538049)

assert fequal(p2.x, 0.1913585038252641)


assert fequal(p2.y, -0.3652272210744360)

if __name__ == '__main__':
test()

We also want to write a benchmark that can measure the performance of our
application. This will provide an indication of how much we have improved
over the previous implementation.

In our benchmark we instantiate 100 Particle objects with random coordinates


and angular velocity, and feed them to a ParticleSimulator class. We then let
the system evolve for 0.1 time units:
from random import uniform

def benchmark():
particles = [Particle(uniform(-1.0, 1.0),
uniform(-1.0, 1.0),
uniform(-1.0, 1.0))
for i in range(1000)]

simulator = ParticleSimulator(particles)
simulator.evolve(0.1)

if __name__ == '__main__':
benchmark()

[ 14 ]
Chapter 1

Timing your benchmark


You can easily measure the execution time of any process from the command line by
using the Unix time command:
$ time python simul.py
real 0m1.051s
user 0m1.022s
sys 0m0.028s

The time command is not available for Windows, but can be found
in the cygwin shell that you can download from the official website
http://www.cygwin.com/.

By default, time shows three metrics:

• real: The actual time spent in running the process from start to finish, as if it
was measured by a human with a stopwatch
• user: The cumulative time spent by all the CPUs during the computation
• sys: The cumulative time spent by all the CPUs during system-related tasks
such as memory allocation

Notice that sometimes user + sys might be greater than real, as multiple processors
may work in parallel.

time also offers several formatting options; for an overview you can
explore its manual (by using the man time command). If you want a
summary of all the metrics available, you can use the -v option.

The Unix time command is a good way to benchmark your program. To achieve
a more accurate measurement, the benchmark should run long enough (in the
order of seconds) so that the setup and tear-down of the process become small,
compared to the execution time. The user metric is suitable as a monitor for the
CPU performance, as the real metric includes also the time spent in other
processes or waiting for I/O operations.

Another useful program to time Python scripts is the timeit module. This module
runs a snippet of code in a loop for n times and measures the time taken. Then, it
repeats this operation r times (by default the value of r is 3) and takes the best of
those runs. Because of this procedure, timeit is suitable to accurately time small
statements in isolation.

[ 15 ]
Benchmarking and Profiling

The timeit module can be used as a Python module, from the command line, or
from IPython.

IPython is a Python shell designed for interactive usage. It boosts tab completion and
many utilities to time, profile, and debug your code. We will make use of this shell to
try out snippets throughout the book. The IPython shell accepts magic commands—
statements that start with a % symbol—that enhance the shell with special behaviors.
Commands that start with %% are called cell magics, and these commands can be
applied on multi-line snippets (called cells).

IPython is available on most Linux distributions and is included in Anaconda.


You can follow the installation instructions in the official documentation at:
http://ipython.org/install.html

You can use IPython as a regular Python shell (ipython) but it is


also available in a Qt-based version (ipython qtconsole) and
as a powerful browser-based interface (ipython notebook).

In IPython and command line interfaces it is possible to specify the number of


loops or repetitions with the options -n and -r, otherwise they will be determined
automatically. When invoking timeit from the command line, you can also give a
setup code that will run before executing the statement in a loop.

In the following code we show how to use timeit from IPython, from the command
line and as a Python module:
# IPython Interface
$ ipython
In [1]: from simul import benchmark
In [2]: %timeit benchmark()
1 loops, best of 3: 782 ms per loop

# Command Line Interface


$ python -m timeit -s 'from simul import benchmark' 'benchmark()'
10 loops, best of 3: 826 msec per loop

# Python Interface
# put this function into the simul.py script

import timeit
result = timeit.timeit('benchmark()',
setup='from __main__ import
benchmark', number=10)
# result is the time (in seconds) to run the whole loop

[ 16 ]
Random documents with unrelated
content Scribd suggests to you:
rough stone slab upon which the offenders were seated still remains
in place.
Stroud is a larger and better-appearing town, whose ten thousand
inhabitants depend mainly upon the manufacture of English
broadcloths. The whole section, in fact, was once the center of cloth
manufacture, but the advent of the steam engine and more modern
methods superseded the watermills. All about are half-ruined factory
buildings, some of them once of vast extent, with shattered windows
and sagging roofs. Here and there one has survived in a small way
or has been adapted to some other industry. In the neighborhood
are many country houses, once the residences of wealthy cloth-
makers, but now either deserted or turned into farm tenements.
The country is hilly and wooded, and we had few points of vantage
that afforded views more picturesque and far-reaching than from
some of the upland roads overlooking these Gloucestershire
landscapes. The road sweeps around the hills, rising at times far
above the valleys, affording a panorama of the Avon gleaming
through the dense green foliage that half conceals it. The vale
presents the most charming characteristics of rural England. One
sees the irregular patchwork of the little fields, the great parks with
their sunny meadowlands and groups of ancient trees, the villages
lying in the valleys or clinging to the hillsides, and the gray church
towers that lend a touch of majesty and solemn sentiment to almost
every glimpse of Britain.
We missed the main road from Bath to Wells, wandering through a
maze of unmarked byroads, and were able to proceed only by
frequent inquiry. We did not regain the highway until just entering
the town and had been a comparatively long time in going a short
distance. After a few minutes’ pause to admire the marvelous west
front of the cathedral, with its endless array of crumbling prophets,
saints and kings, weatherworn to a soft-gray blur, we were away on
the highroad leading across the wold to Cheddar, famed for its
stupendous cliffs, its caverns—and its cheese. The caverns and cliffs
are there, but little cheese now comes from Cheddar, even though it
bears the name. As we ascended the exceedingly steep and winding
road we were astonished—overwhelmed. We had not expected to
find natural scenery upon such an amazing scale in the heart of
England—gray pinnacled cliffs rising, almost sheer, five hundred feet
into the sky. Not often may British scenery be styled imposing, but
the towering cliffs of Cheddar surely merit such description. In the
midst of the gorge between the great cliffs there are two prehistoric
caverns extending far into the earth. We entered one of them, now a
mere passageway, now a spacious cavern whose domelike roof
glistens with translucent stalactites. Here we pass a still, mirrorlike
pool, and there a deep fissure from which comes the gurgle of a
subterranean river. Altogether, there is much that is interesting and
impressive. Perhaps it all seems a little gaudy and unnatural because
of the advertising methods and specious claims of the owner and
alleged discoverer, but none the less a visit is worth while. The
museum of relics found in the cavern contains a remarkable
prehistoric skull, with low, thick frontal bone and heavy square jaw,
but its queerest feature is little spurlike projections of the temporal
bone just above the ear. It is estimated by archaeologists that the
possessor of this curious skull had lived at least forty thousand years
ago and mayhap had made his dwelling-place in the Cheddar Caves.
We were assured that an offer from the British Museum of five
thousand pounds for the relic had been refused.
The sun was low when we left Cheddar, and Taunton seemed the
nearest place where we might be sure of good accommodations. We
soon reached Axbridge, a gray little market town, so ancient that a
hunting-lodge built by King John still stands on the market square.
Near Bridgewater, a few miles farther, is the Isle of Athelney—once
an island in a marsh, perhaps—where King Alfred made his last
desperate stand against the Danish invaders, defeating them and
finally expelling them from Britain. Not less in interest, though
perhaps less important in its issues, was the Battle of Sedgemoor,
fought here in 1685, when the Duke of Monmouth was disastrously
defeated by the Royal Army—the last battle worthy of the name to
be waged on English soil.
But we were to learn more of Monmouth at Taunton and to have
again impressed upon us how easy it is in Britain for one to hasten
through places of the deepest historic interest quite unaware of their
tragic story. We had passed through Taunton before, seeing little but
a staid old country town with a church tower of unmatched
gracefulness and dignified proportions; but Taunton’s tragic part in
the parliamentary wars and her fatal connection with “King
Monmouth” never occurred to us, if, indeed, we knew of it at all.
Taunton was strongly for the Parliament, but it was a storm center
and was taken and retaken until the iron hand of Fairfax crushed the
Royalists before its walls. Its record stood against it when the King
“came into his own again.” Its walls were leveled to the ground, its
charter taken away and many of its citizens thrown into prison.
Discontent and hatred of the Stuarts were so rampant that any
movement against their rule was welcomed by the Taunton Whigs,
though it is hard to see any consistency in the unreasoning support
they gave to the Duke of Monmouth—the son of Charles II. and one
of his many mistresses—in his pretensions to the throne occupied by
James II. Monmouth entered Taunton amidst the wildest
acclamations, and it was from the market square of the rebellious
town that he issued his proclamation assuming the title of King. He
was followed by an ill-organized and poorly equipped army of seven
thousand men, who were defeated by four thousand Royal Troops.
Then followed a reign of terror in Taunton. The commander of the
King’s forces hanged, without pretense of trial, many of his
prisoners, using the sign of the old White Hart Inn as a gallows.
Then came the Bloody Assizes, held by Jeffreys of infamous memory,
in the great hall of the castle. After trials no more than travesties of
brutal jests and savage cruelty, more than three hundred
Somersetshire men were sentenced, according to the terrible
customs of the time, to be “hanged, drawn and quartered,” and a
thousand were doomed to transportation. Here the active history of
Taunton may be said to have ended.
But Taunton has little to remind us of these dark and bloody times as
we glide through her fine old streets and draw up in front of the
London Hotel, where the host himself in evening dress welcomes us
at the door. Every attention is given us and The London certainly
deserves its official appointment by the Royal Automobile Club as
well as the double distinction accorded it by the infallible Baedeker.
It is one of the charming old-fashioned inns, such as perhaps
inspired the poet Shenstone with the sentiment expressed in his
well-known quatrain:

“Whoe’er has traveled life’s dull round,


Whate’er his stages may have been,
May sigh to think that he has found
His warmest welcome at an inn.”

Modern Taunton is a city of some twenty thousand people, and


being the county town, with some manufactories, it enjoys a quiet
prosperity. Of its ancient landmarks, the castle, dating from the
eleventh century, is the most notable and has appropriately been
turned into a museum. Here one may enter the hall where Jeffreys
held his court. Though two centuries or more have elapsed, the
“horror of blood” seems still to linger in the gloomy apartment. The
market-place retains its old-time characteristics, and though the
house occupied by Jeffreys has disappeared, the White Hart Inn still
stands. But the glory of Taunton is St. Mary’s Church, one of the
most graceful examples of the Perpendicular period in England. The
splendid tower seems almost frail in its airy lightness—and perhaps it
is, for it is a recent restoration, or rather replacement, of the older
one, which had become insecure.
Sherborne Abbey we had missed in our former wanderings, though
once very near it, and we felt that we must make amends though it
cost us a detour of sixty miles. And yet, what hardship is it to go out
of one’s way in Britain? Indeed, can one ever go out of his way in
rural England? Scarcely, from the point of view of such nomads as
ourselves.
The great tower of Curry Rivell Church dominates in such a lordly
manner the village straggling up the hill toward it that we were
tempted to look inside, and a mild curiosity was aroused, from which
we have never yet been able to rid ourselves. For, chained to one of
the iron railings of a sixteenth century tomb, is a queer little iron-
bound oaken cabinet. It is scarcely more than a foot in length, the
wood is worm-eaten and the massive lock and heavy hinges are red
with rust. What mystery does it contain and why did it escape the
church-looters of Puritan times? The church is rich in antique
carvings, among them a delicately wrought screen and fine fifteenth
century bench ends. The tomb to which the coffer is chained is a
very unusual one. It bears on its altar the effigies of two mail-clad
warriors, while at either side kneel figures of their wives over two
tiny cribs with several gnomelike children tucked in each. Overhead,
borne by four pillars, is a domed canopy upon which are painted
four sprawling cherubs. All very quaint and strange and illustrative of
the queer mortuary ideas of the medieval period.
We followed the winding, hilly and often indifferent road that leads
through Somerton, Ilchester and Yeovil to Sherborne, and while our
lunch was preparing at the slow-moving Antelope—there is little in a
name, in this instance—we wandered down old-world streets to the
abbey, the goal of all pilgrims to Sherborne. It seemed odd to find
the old town crowded with rural visitors all agape at a fantastic
circus parade that was winding along the crooked streets, but
Sherborne is fond of parades and pageants, for we were assured
that the historical pageant now the rage in the older towns of
England was originated in Sherborne. The town itself is a charming
place—I borrow the words of an enthusiastic admirer whose picture
may be better than I can paint:
“It is a bright town, prim and old-fashioned, and unsullied by the
aggressive villas and red brick terraces of the modern suburb.
Although a small place, it is yet of much dignity. Here are timber-
faced dwellings, where the upper story overhangs the lower, and
where the roof breaks out into irrelevant gables; houses with the
stone-mullioned casements of Tudor days or the round bow window
of the Georgian period; houses with gateways under them leading
into courtyards; humble buildings fashioned out of stone filched from
a church; cottages with the arched doorways of a convent or with
buttresses worthy of a chapel; pieces of old wall and other
miscellaneous fragments which the town with its love for the past
has never had the heart to cast aside. Over the grey roofs can be
seen the trees upon the hilltop, while over many a crumbling wall
comes the fragrance of garden or orchard.”
But as we rounded a corner and came upon a full view of the abbey
church, we felt that it had rightly been styled the “glory of
Sherborne.” Perhaps its low tower gives an impression of
incompleteness and lack of proportion—but it seemed to accentuate
the mighty proportions of the church itself and it was with a feeling
almost verging upon awe that we entered the majestic portals. And
we learned it as we know only few historic churches in England, for
the gem of all vergers is at Sherborne. To him his work is a labor of
love, not the usual perfunctory performance in hope of a fee. He had
made discoveries of importance himself in whiling away his time in
the abbey and had located and uncovered an ancient effigy that had
been inconsiderately built into the walls in earlier days. He told us of
the checkered history of the abbey, of the wars of the monks and
citizens, as a result of which the church suffered from a great fire,
the marks of which still remain in the red stains on the soft yellow
stone, of the Dissolution and the cavalier manner in which Henry the
Wrecker bestowed the abbey on one of his friends, who in turn sold
it to the parish for two hundred and fifty pounds—all of which would
be too long to record in detail in this crowded chronicle. But the
interior of Sherborne Abbey—where is there another like it? Not in all
England; probably not in the world. It lacks the “dim religious light”
that pervades, like a soft-toned mist, most of the great church
buildings; the windows flood the yellow stone with many-colored
beams and lighten the splendors of the golden fan vault with its rich
bosses and heraldic devices until every detail comes out clearly to
the beholder below.
But we are lingering too long at the abbey; we were to return to the
Antelope in half an hour, and thrice that period has elapsed. We hie
back to our inn and do not complain of our cold repast. “It is ten
minutes’ walk to the castle,” said our host. Then why take the car? A
ten minutes’ walk will give us a little of the exercise we need. We
start under the sweltering sun—it is a hot day, even as we reckon it
—and follow the crooked streets. Here is a high wall—it must be the
castle. No, the castle is farther on; and we repeat the wearisome
experience until half an hour has elapsed and we are only at the
entrance gate of the park. We are almost exhausted, for our long
tramp on the “abbey stones” did not especially invigorate us, but we
will go on after having come so far.
It was hardly worth while—Cromwell had left very little of Sherborne
Castle. It seemed melancholy, indeed, that the riddled gateway and
the straggling pieces of wall should be all that remains of such a
lordly building. We were interested to know that it had been granted
to Sir Walter Raleigh “forever” in 1597—but only six years later the
knightly founder of Virginia was indicted for treason and fell a victim
to the cowardly malice of King James, and Sherborne Castle reverted
to the crown. It was less than half a century later that Fairfax
received its surrender in the name of the Parliament, and when the
gunpowder mines were fired the active days of the fortress were at
an end.
We retrace our steps to the Antelope, thinking mournfully of the car,
which would have made such short and easy work of our weary trip,
and we heave a sigh of relief when once more, having donned our
“seven-league boots,” we hear the soft purr of the motor and enjoy
the rush of the cool, sweet air—after our “ten minutes’ walk.”
It grows late and Exeter is far away, but we are sure of comfort at
the Rougemont and we give the car rein. How she sweeps over the
sunset hills and glides along the cool valleys, pausing cautiously to
pass some rose-embowered village, now gathering speed again for
another rush over the fine road! She is ahead of schedule at
Honiton, and one of our party remembers that the Honiton lace is
famous. It is an expensive bit of recollection, but all things go in a
motor tour. After a half-hour’s pause, we are away again, and before
long catch sight of the huge bulk of Exeter Cathedral looming above
the old city against the twilight sky.
V
RAMBLES IN THE WEST COUNTRY
“Through the heart of Dartmoor forest” may bring up many
fascinating, even weird associations, but on our map we regarded
the thin red line of our road rather dubiously. It runs almost straight
from Exeter to Prince Town—the prison town of the moor—and on
either side for many miles lies a waste country, apparently quite
devoid of villages and even of roads. The road as shown on the map
is thickly studded with arrow heads, denoting dangerous hills, and
the description in the road-book is far from alluring. But we were not
to be deterred from exploring Dartmoor, as we had been on a
previous occasion, though indeed we found the first few miles
between Exeter and Moreton Hampstead trying and almost terrifying
in places. The hills offered little impediment to our motor, but for all
that one has a rather eery feeling when clinging to a precipitous
incline. If something should let loose! But nothing did.
Moreton Hampstead is a bleak, lonely little town set well into the
western edge of the moor and surrounded by rugged tors on every
hand. It is not without a bit of antiquity, for it has a sixteenth
century building, called the Arcade, whose Moorish touches are
decidedly picturesque. It is like a bit of Spain in the hills of Dartmoor
and seems strangely out of place. Only three miles from Moreton
Hampstead, lying in a secluded valley, is Chagford, famous for its
quaint old inn and wild surroundings.
Once out of Moreton Hampstead and away on the yellow highway
that bisects the moor, we found ourselves in a country as barren as
any we had seen in England. The road, though winding and steep, is
generally visible for some distance ahead, and we found little
hindrance to a swift, steady flight that carried us over the long hills
far more quickly than we anticipated. The day, which had begun in
mist and rain, became lighter and a rapidly clearing sky gave us the
opportunity of seeing the wild beauty of the moor at its best.
Despite its loneliness and cheerlessness, there was a wonderful play
of color: the reds and browns of the broken granite, the purple blaze
of the heather, the vivid yellow of the gorse and the metallic green
of the whortle, all intensified by golden sunshine, have marvelously
transformed the somber tone of the moorland of scarce an hour
before. But where is the “forest”? Only stunted trees appear here
and there, or a fringe of woods along the clear streams; we learn
that “forest” once meant a waste, uncultivated tract of land, and in
later days has been applied to woodlands alone. We run for miles
with no human habitation in sight save an occasional cottage in a
small, barren field surrounded by stone walls. We come upon a
large, attractive-looking inn unexpectedly—though it ought not to be
unexpected to find an inn anywhere in England—the Two Bridges,
situated near the head waters of the Dart, here no more than a
brawling streamlet. We leave the car by the roadside and enter the
homelike hall, where an array of fishing-tackle makes clear the
excuse for this pleasant hotel in the moor. The day has been chilly
and, strange to say, a fire flickers in the grate. We are just in time
for luncheon and a goodly number of guests respond to the vigorous
beating of the gong—that almost universal abomination of the
provincial English hotel. It appears that the quiet and seclusion of
Dartmoor is not without its attractions to many people. We ourselves
leave the pleasant inn with regret; we should have liked a day’s rest
in the cozy ingle-nook.
IN SUNNY DEVON.
A view of the old town of Totnes from the upland road.
Original Painting by George Bowman, 1908 Royal Academy.
The walls and battlements of Prince Town Prison soon loom in sight.
This was established in 1800 as a military prison for French soldiers,
and a few Americans were confined here in 1812. It then fell into
disuse until 1850, but for the half-century since it has served its
present purpose as a penal institution and has been greatly added to
from time to time.
An English writer says: “Dartmoor is so huge that one must be born
and spend a lifetime near it to really know it, and the visitor can
merely endeavour to see typical examples of its granite tors, its
peaty streams, its great stretches of boulder-strewn heather, and its
isolated villages.” Evidently he must mean that it is huge in its
mysteries and its moods, for it is really only fourteen by twenty-two
miles—perhaps half as large as the average county in the United
States.
At Tavistock we are well beyond the confines of the moor and follow
a fine road to Launceston, where we glance at the huge circular
keep of the castle and look longingly at the White Hart, which recalls
only pleasant memories. But we are bound for an enchanted land
and, like many a gallant knight of yore, we would hasten past
“many-towered Camelot” to the castle of the blameless king. The
declining sun, toward which we rapidly course, seems to flash across
the Cornish hills the roselight of the old Arthurian romance, and the
stately measures of the “Idyls of the King” come unbidden to our
minds. But we soon have something less romantic to think of, for in
attempting a short cut to Tintagel without going to Camelford, we
run into a series of the crookedest, roughest lanes we found in all
England. These appear to have been quite abandoned; in places
mere ravines with myriads of sharp loose stones and many long
steep hills. But we push on and almost ere we are aware, find
ourselves in Tintagel village, which with its long rows of boarding-
houses hardly accords with one’s preconceived romantic notions.
Then we catch a glimpse of the ocean out beyond the headland,
upon which is perched a huge, square-towered building—King
Arthur’s Castle Hotel, they tell us—and thither we hasten. This hotel,
only recently completed, is built on a most liberal scale, though it
can hardly accommodate many guests at a time. The public rooms
are most elaborately furnished and of enormous size. The great
round table in the reading room is a replica of the original at
Shrewsbury, at which, declares tradition, King Arthur sat with his
fifty knights. The guest rooms are on an equally generous scale and
so arranged that every one fronts on the sea. The rates are not low
by any means, yet it is hard to conceive how such a hotel can be a
paying investment.
After we reached the hotel, the long twilight still gave time to
contemplate the weird beauty of the surroundings and to explore the
ruins of the castle so famed in song and story. We scrambled down
the high headland, upon which the hotel stands, to the level of the
blue inlet of the sea, depicted in such a masterly manner in the
painting by Mr. Moran, the towering cliffs crowned by the
fragmentary ruins looming far above us. A path cut in the edge of
the cliff leads to a precarious-looking foot-bridge across the chasm
and a still narrower and steeper path hugs the face of the precipice
on the opposite side until a heavy oaken door is reached. This door,
to which the old caretaker in the cottage below had given me the
key, opens into the supposed site of King Arthur’s castle. Only a few
scattered bits of masonry remain and these are probably of a later
time than that of the early Briton.

KING ARTHUR’S CASTLE, OFF TINTAGEL HEAD, CORNWALL.


From Original Painting by Thos. Moran, N. A.
The spot is lonely and quite barren save a few patches of
greensward upon which were peacefully grazing a flock of sheep—
one finds them everywhere in Britain. I was quite alone—there were
no other visitors at that late hour and my companions had given up
the dizzy ascent before it was fairly begun—and I strove to
reconstruct in imagination the castle as it stood in the days of the
blameless king. How the wild old stories crowded upon me in that
lonely twilight hour! Here, legend declares—and I care not if it be
dim indeed and questioned by the wiseacres—was once the court of
the wise and faultless Arthur, who gathered to himself the flower of
knighthood of Christendom and was invincible to all attacks from
without, but whose dominion crumbled away before the
faithlessness and dishonor of his own followers. Here, perchance,
the faithless Guinevere pined and sighed for her forsworn lover and
gazed on the sea, calm and radiant as it is even now, or saw it lash
itself into unspeakable fury upon the frowning bastions of the coast.
But, alas! how dim and uncertain is all that is left, and how the tales
vary save that they all center in the king! Little remains in local
tradition of all the vanished splendors of those ancient days save
that the king did not die; that in the form of a chough he haunts the
scenes of his glory and his downfall, and that he will come again—
But I am quite forgetting the flight of time, and with a lingering look
at the storied spot, I slowly descend. Then I climb to the more
extensive ruin on the landward side, much shattered but grim and
massive in decay. There must have been a connection between the
castles on either side of the great ravine, though it is hardly
apparent how this could have been. Perhaps the gap has widened
much in the long course of time. It is dusk when we return to the
hotel and sit long on the open terrace fronting the sea,
contemplating the beauty of the scene.
Never have I beheld a more glorious sunset than that which
lightened the wild Cornish coast and ocean on that particular
evening. A dark band of cloud lay low along the western horizon,
with a clear, opalescent sky above, and below a thin strip of lucent
gold with silvery clouds floating in it like fairy ships. Suddenly the
sun dropped from behind the cloud, which had obscured his full
splendor, into the resplendent zone beneath, flooding the sea, into
which he slowly sank, with a marvelous though evanescent glory.
Then followed all the indescribable color changes and combinations,
which varied momentarily until they faded into the dusky hues of a
moonlit night. It marked the close of a perfect day—clear and cool,
with sky of untainted blue and ocean as still and glassy as a quiet
inland lake.
Not less inspiring was the scene that greeted us through our open
lattices in the morning—a sea steely blue in the distance, rippling
into bars of frosted silver near the shore, while the stern outlines of
the headlands were softened by a clinging blue haze. We lingered on
the legend-haunted ground until nearly noon and it was with keen
regret that we glided away from the pleasant hostelry back to the
village and past the old church on the headland, whose bells tolled
without mortal hands on the far-off day when the body of King
Arthur was borne away to sepulture in Glastonbury Abbey.
A fine upland road led us nearly due north from Camelford through
long stretches of moorland—or country almost as sterile as the
moors—diversified with great patches of gorse and scattered groups
of stunted trees. We encountered scarcely a village for a distance of
twenty-five miles, for we did not turn aside for Bude or for Stratton,
just opposite on each side of the road. The latter is said to be one of
the most unspoiled and genuinely ancient of the smaller Cornish
villages. At times we were within a mile or two of the ocean and
caught fugitive glimpses of blue expanses of quiet sea. Then the
road sweeps farther inland and the country improves in appearance,
though it is still Cornwall and Devon and far different from the sleek,
prosperous beauty of the Midlands.
OFF THE COAST OF DEVON.
From Original Painting by A. J. Warne-Browne.
“The most exquisite town in England,” writes an enthusiast of
Clovelly, but Clovelly’s very quaintness has made it so widely known
that it hardly has a place in a chronicle that seeks rather the
untrodden ways. It is not possible for a motor or any other vehicle to
descend the steep, stone-paved streets, and about a quarter of a
mile above the town we left the car in an exceedingly prosperous-
looking stable-yard filled to overflowing with motors, carriages and
chars-a-bancs.
Clovelly well deserves its reputation for the picturesque qualities that
have transformed it from an unpretentious fishing village, lost
among the clifflike hills, into a thronged tourist resort. Fortunately,
as yet there has been no attempt to modernize; no stucco-and-
timber hotel detracts from the antique flavor; the people who come
to Clovelly do not as a rule stay long. Large excursion steamers,
usually crowded, ply from Ilfracombe, and coaches and chars-a-
bancs from Hartland and Barnstaple bring troops of visitors.
Coaching parties come from Tintagel (round trip eighty miles) and
one is sure to find Clovelly crowded in season, especially if the day is
fine. And so we found it, literally thronged, a huge excursion
steamer lying at anchor in the harbor. There was a little disarray and
confusion at the pleasant New Inn—new in name only—evidently
due to more patronage than could easily be taken care of. As we
waited for luncheon we looked about at the collection of antique
brass, copper, china and pottery that almost covered the walls and
crowded the mantelpieces and odd corners about the inn. We were
told that the landlady is a famous collector and that many of the
pieces are rare and valuable. A more amusing if not less interesting
feature of the house is the sentiment expressed in halting doggerel,
emblazoned in large red letters on the walls and ceiling of the
dining-room. It is good only from the standpoint of exceeding
badness, and its general tenor is to flatter Americans, who no doubt
constitute a large proportion of the guests.
The old, time-worn churches of England are past numbering and
they came to have an almost weird fascination for us. The tombs,
ranging from the artistic to the ghastly or grotesque, the old stones
with their often queer or even ridiculous epitaphs, the sculptures,
the bosses, the frescoes, the stained windows, the gargoyles and
the oftentimes strange history or still stranger legends connected
with nearly every one—but why prolong the list of curious attractions
of these ancient fanes, often quite peculiar in each case? Just before
we entered Barnstaple we turned into a byroad, and dropping down
a hill of appalling steepness and length, came to Tawstock Church,
famed as the finest country church in Devon—the “Westminster of
the West Country,” some enthusiast has styled it. Though hardly
deserving such a dignified characterization as this, Tawstock Church
is well worth a visit. Besides some remarkable tombs and fine
Elizabethan pews, it has a peculiar gallery curiously wrought in vine
and leaf pattern from black oak, and now used by the bell-ringers to
reach the tower. Tawstock Mansion, near by, appears rather modern
—a large building shining in a fresh coat of yellow paint that gave it
much the appearance of a summer hotel. The house and church are
located in a deep wooded valley and the towers of the ancient
gateway lend a touch of much-needed antiquity to the scene.

TAWSTOCK CHURCH, DEVONSHIRE.


Barnstaple, like Bideford, while a very old town, has few old-time
relics now left. It has become a manufacturing town, its chief
product being Barum ware, an inexpensive grade of pottery. The
Golden Lion Inn, once a residence of the Earl of Bath, is famed as a
place of solid comfort, and still retains much of the gorgeous
decorations done by its former occupant. The poet Shelley had an
odd association with Barnstaple. When living at Lynton, after his
marriage with Harriet Westbrook, he came to Barnstaple and spent
some time in bringing out a pamphlet scurrilously attacking the chief
justice who had sentenced to prison the publisher of the works of
Thomas Paine. One of the poet’s associates, who distributed the
pamphlets, was sentenced to six months in jail, and Shelley narrowly
escaped by hastily leaving the town.
The road from Bideford through Barnstaple and Ilfracombe is rather
uninteresting, save the last few miles, which pass through wooded
hills and along deep verdant valleys. Ilfracombe is a resort town,
pure and simple, and we found few hotels on a grander scale than
the Ilfracombe, standing in beautiful grounds facing the sea, which
murmured almost directly beneath our open windows. It was a
beautiful evening; the tide was just receding from the jutting rocks
scattered along the coast, whereon the sea, even in its mildest
moods, chafes into foam; and one can easily imagine a most awe-
inspiring scene when the angry ocean, driven by a westerly wind,
assails these bold, angular rocks. After having visited every resort
town of note in England, our recollection is that of all, Ilfracombe is
the most strikingly situated; nor do any of them command views of a
coast line more rugged and picturesque.
The rain was falling heavily when we came to Dunster on the
following day and the abbey church was gloomy indeed. And what
can be gloomier than an old church on a gray day, when the rain
pours from the low-hung clouds and sweeps in fitful gusts against
the mossy gravestones and crumbling, ivy-clad walls? A scene that
renders one solemn and thoughtful on almost any occasion becomes
positively depressing under such conditions. And though we recall
Dunster Church with associations not unpleasing in perspective, the
surroundings were not altogether pleasing at the time. We found the
caretaker, a bent old woman, in the church, but she informed us that
there were really two churches and that she had jurisdiction over
only one of them. However, she conducted us about the dimly
lighted building, gloomy indeed from the lowering skies without, and
our recollection of her story of the quarrel that resulted in the
partition of the church has faded quite away. But we do remember
the rood screen which has fourteen separate openings, no two
wrought in the same pattern and altogether as marvelous a piece of
black-oak carving as we saw in England.
Aside from the abbey church, there are other things of interest in
Dunster, especially the market cross and the castle. The latter
overlooks the town from a neighboring hill and is one of the lordliest
fortresses in the West Country. The town lies in one of the loveliest
vales in Somersetshire and is famed for its beautiful surroundings.
This section of Somerset and Devon is rich in literary associations; at
Nether Stowey we pass the square, uncomfortable-looking house,
close to the roadside, where Coleridge lived for three years,
beginning in 1797. Indeed, it was in the autumn of that year that he
made the excursion with Wordsworth and Dorothy, during which the
plan of the “Ancient Mariner” was conceived. A few months before,
while in a lonely farmhouse between Porlock and Lynton, he had the
dream which he started to record in “Kubla Khan.” This poem he had
composed in his dream, but while writing it down on awakening, a
“person from Porlock” interrupted, and when the poet essayed to
write, not only the words but the images of the vision had faded
away, and the fragment of “Kubla Khan” remains like a shattered
gem. Wordsworth and his sister Dorothy came a little later to
Alfoxden House, standing in a pleasant park in the parish of Halford,
and here the literary association between Coleridge and Wordsworth
became intimate and the little volume of “Lyrical Ballads” was
published jointly by them in 1798. Southey, while storm-stayed by
“an unwelcome summer rain” at the Ship Inn in Porlock, wrote a
sonnet in praise of the hills and glens. Hazlitt and Charles Lamb at
times joined their friends here for pedestrian excursions among the
hills. Nor can we forget Blackmore, whose “Lorna Doone” turned the
eyes of the English-speaking world toward the Exmoor wastes.
Shelley’s escapade at Barnstaple we have already mentioned and the
cottage he occupied at Lynton still stands. No doubt much of the
weird beauty that pervades his work entered his soul amidst the
glorious surroundings—the sea, the hills and the vales—of the West
Country.
EVENING ON THE CORNISH COAST.
From Original Painting by A. J. Warne-Browne.
A pause at Cleeve Abbey near at hand gave us perhaps a better idea
of the life of monastic days than any other we visited—and we saw
all the greater abbeys of Britain. In the majority of cases the abbey
proper had been destroyed, but the church escaped, often through
purchase by the citizens. At Cleeve the reverse has happened; the
church has totally disappeared, but the abbey buildings are nearly
intact. As a well-informed writer puts it:
“The whole life of the society can be lived over again with but little
demands on the imagination. We can see the dormitories in which
they slept, the refectory where they fed, the abbot’s particular
parlour and the room for accounts, the kitchen, and even the
archway through which their bodies went out to the grave. The
church suffered from despoilers more than any other part of the
abbey, and great is the loss to architecture. Otherwise we get a
community of the Middle Ages preserved in all its essential
surroundings, the refectory being in particular a grand fifteenth-
century hall.” The ceiling of this great apartment is of the hammer-
beam pattern, the beams richly carved, and, springing from oaken
corbels, figures of angels with expanded wings.
It brings one near indeed to the spirit of monastic days—this gray
old ruin, through which sweep the wind and rain and where under
foot the grass grows lush and green as it grows only in England—the
spirit which the Latin legend over the gatehouse so vividly
expresses, quaintly rendered thus:
“Gate Open be
To honest folk as free.”

And the gray-whiskered custodian, so rheumatic and feeble that his


daughter, a husky peasant woman, guides visitors about the abbey,
warmed up to us as we were about to leave and opened his heart
about the ruin in which he dwelt and which he seemed to love. He
told us its story in the broad West Country dialect and pointed out to
us many things of curious interest that we otherwise should have
overlooked.
The sky is clearing; the low sun flashes along the hill-crests and
floods the Somerset landscape with ethereal beauty, which we drink
in as we skim swiftly along the smooth, wet road. We catch a final
gleam of the ocean at Weston-super-Mare and pass a long row of
imposing hotels. Then we are away for Bristol, the Queen City of the
West Country.
VI
ODD CORNERS OF THE WELSH
BORDER
There are few English castles where the spirit of medievalism lingers
as at Berkeley and few that have darker deeds recorded in their long
annals of crime. It has had a strange fascination for me ever since I
read its story in my boyhood days, and the verse of the poet Gray
had given the castle a weird association in my mind:

“Mark the year and mark the night


When Severn shall echo with affright;
When shrieks of death through Berkeley’s roofs shall ring,
Shrieks of an agonizing king.”

It was therefore a keen disappointment to learn on arriving in the


quiet Gloucestershire town that it was not a day when the castle was
open to visitors. However, we do not regret this so much in
retrospect. The castle, grim, many-towered, ivy-clad, the very
embodiment of the days of chivalry, still lingers in memory, with
nothing to disenchant its mystery and romance. The old keeper at
the imposing entrance was evidently sincere in his regret that the
rule might not be suspended for our benefit—for indeed we had
found such regulations not as the laws of the Medes and Persians,
but there was no such good fortune here. “But do not fail,” said he,
“to view the castle from the meadows, for no finer sight will you find
in England.”
If there be finer views of other English castles—a mere matter of
opinion, after all—there can hardly be a better viewpoint than the
Berkeley Meadows. It is a wide expanse of lawnlike meadowland
lying alongside the castle, which stretches out its battlemented and
turreted length against a background of majestic trees; from these
rises the square church-tower in stern outline against the bluest of
English June skies. The scene indeed savors more of enchantment
than reality, and the environment seems fitting to the historic pile
where a king was done to death and which Shakespeare mentions
more than once. The present owner is the twenty-seventh in direct
descent from Robert Fitzhardinge, to whom the manor was originally
granted and who built a large part of the present castle in the tenth
century.
The view from the castle keep is described by one who has written
much of its legends and history: “Northwards and southwards the
broad Vale of Berkeley, rich with verdure of pasture and woodland,
runs on into the far distance. To the east and southeast are the
Cotswolds, rising abruptly here and there into bold, bare masses
whose sides are clothed with beech woods, and anon retiring into
lovely valleys which seem to invite the eye to range their recesses.
On the west flows the broad estuary of the Severn, studded with
many a white sail; beyond it are the dark wooded hills of the Forest
of Dean, veiled by the smoke of its iron-works and collieries. Under
the walls of the castle, on the north and west sides, the little town
seems to nestle, as though seeking shelter and protection from the
grim old fortress, which was probably its origin and has been its stay
and support through so many generations.”
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookname.com

You might also like