In this notebook we'll look at some of the issues surrounding executing code in the notebook.
When you interrupt a computation, or if an exception is raised but not caught, you will see a backtrace of what was happening when the program halted. The backtrace is color highlighted to help you find the information you need to debug the problem.
In [1]:
def f(x):
return 1.0 / x
def g(x):
return x - 1.0
f(g(1.0))
You can also turn on the Python debugger inside a notebook using the
magic invocation %pdb on
. When an exception occurs, the debugger
will activate inside the output cell. You can then type commands
and see responses from the stopped state of the program.
Some commands:
h
helpw
print stack tracep expr
print expressionsq
quitr
restartFull documentation on the debugger can be found at Python debugger pdb.
In [2]:
%pdb on
f(g(1.0))
In [3]:
import sys
print('Hello, world!')
sys.stdout.write('We meet again, stdout.')
sys.stderr.write('Error, you appear to have created a black hole.')
In [4]:
import time
for i in range(10):
print(i)
time.sleep(0.5)
In [5]:
import threading
class SummingThread(threading.Thread):
def __init__(self, low, high):
super(SummingThread, self).__init__()
self.low = low
self.high = high
self.total = 0
def run(self):
for i in range(self.low, self.high):
self.total += i
def sequential_sum(n):
total = 0
for i in range(0, n):
total += i
return total
def parallel_sum(n):
thread1 = SummingThread(0, n/2)
thread2 = SummingThread(n/2, n)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
return thread1.total + thread2.total
%timeit sequential_sum(100000)
%timeit parallel_sum(1000000)
In [ ]:
from time import sleep
from multiprocessing import Pool
def f(p):
low, high = p
total = 0
for i in range(low, high):
total += i
return total
def sequential_sum(n):
total = 0
for i in range(0, n):
total += i
return total
def parallel_sum(n):
p = Pool(2)
results = p.map(f, [[0, n/2], [n/2, n]])
return results[0] + results[1]
if __name__ == "__main__":
%timeit sequential_sum(1000)
%timeit parallel_sum(1000)