Exercises 14.5 and 14.6 describe two of the improvements that can be made to the efficiency of Listing 14.1. Because they reduce the number of loop executions, they must make the program faster, but by how much? Is the improvement significant? Measuring program performance is one way to analyze the impact of changes made to your code.
In Python, we can get reasonably accurate timings using this function from the time module:
clock() |
Current processor time. |
The standard way to use a clock is to surround the code you want to measure with two calls to the clock, like this:
start = time.clock()
sieve(10000)
stop = time.clock()
elapsed = stop − start
The variable elapsed will then hold the time it took to execute the function. Be sure not to put any other code between the two calls to the clock.
primes[i] = True |
If i is not crossed off (potential prime). |
primes[i] = False |
If i is crossed off (not prime). |
Write a function sieve2(n) to compute and return the boolean list that results from using this technique to implement the sieve.
sieve(n)
primelist(n)
sieve2(n)
Report and discuss your results.
3.142.114.245