Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Math 152: Intro to Mathematical Software
2017-02-08
Kiran Kedlaya; University of California, San Diego
adapted from lectures by William Stein, University of Washington
Lecture 13: Timing and Speed
Timing your code
Here's some code. It is intentionally naive in various ways...
Explain this code line by line:
define function of one input
Docstring
sin(m) is the sage symbolic sin function
(sin(m) for m in xrange(1,n))
is like a list comprehension but it is "lazy" so it doesn't waste memory -- you can iterate over it though.sum(...)
iterates over its input summing it upfloat(...)
converts its input to a float
Throw out a mathematical question: Is there a simple formula for similar to the formula ?
Is it slow?
Or is the network (or SMC) just slow at sending the answer back?
If it is slow, why?
There are many ways to time execution of code:
Very naive: use a stopwatch. Start the code running and start a stopwatch on your phone or whatever. Look at the wall clock.
Python: use the
time
module, and printsPython: use the
timeit
module, and better printsIn worksheets:
%time
and%timeit
In Sage:
cputime
andwalltime
functions.Using
%prun
in a terminal (so create a terminal and type "sage"). This is an ipython feature.
And there are also many, many ways to speed up code...
3: timeit module: see https://docs.python.org/2/library/timeit.html
Hmm, let's check the documentation. Aha!
4: %time, %timeit commands to SMC
5: cputime
and walltime
functions
Discuss the difference between cpu and wall time.
6: Using %prun in a terminal
+New --> Terminal.
type
sage
to start sage.Define the function.
Use
%prun sin_sum(10000)
Exercise: Try to make sin_sum faster and time the result in several ways. Ideas for how:
replace
m
byfloat(m)
replace
sin
bymath.sin
Of course, you can also try to make the function faster using mathematical knowledge! Can you find an explicit formula for ?