6. The Standard Library
Activity 15: Calculating the Time Elapsed to Run a Loop
Solution:
- We begin by opening a new Jupyter file and importing the
random
andtime
modules:import random import time
- Then, we use the
time.time
function to get thestart
time:start = time.time()
- Now, by using the aforementioned code, we will find the time in nanoseconds. Here, the range is set from 1 to 999:
l = [random.randint(1, 999) for _ in range(10 * 3)]
- Now, we record the finish time and subtract this time to get the delta:
end = time.time() print(end - start)
You should get the following output:
0.0019025802612304688
- But this will give us a float. For measurements higher than 1 second, the precision might be good enough, but we can also use
time.time_ns
to get the time as the number of nanoseconds elapsed. This will give us a more precise result, without the limitations of floating-point numbers:start = time.time_ns() l = [random.randint(1, 999) for _ in range(10 * 3...