It is really good to know whether the code you wrote is efficient or fast. We can test that by checking how long it takes to execute certain commands, or functions.
Computing Execution Time With “time” Module
One way to get the execution time is to use the built-in time module and its function time.time.
Let us say we want to compute the execution of time of creating a list with for loop
my_list = [] for i in range(1000000): my_list.append(i)
and compare that with creating a list in a single line with List Comprehension. By now you might have heard a number of times that for loop is typically slower. Let us test that by computing execution time.
Execution time “for loop”
Let us first import the time module.
>import time
Let us use time.time function to get the starting time and then create a list with for loop
# get starting time >start = time.time() # initialize empty list >my_list=c[] # populate the list with for loop >for i in range(1000000): my_list.append(i) # get time taken to run the for loop code >elapsed_time_fl = (time.time() - start) 0.144280910492
Execution time for “list comprehension”
Let us compute execution time for creating the list with list comprehension.
>start = time.time() >my_list = [i for i in range(1000000)] # get time taken to run list comprehension >elapsed_time_lc=(time.time()-start) >0.0875291824341
We see that for creating same number of elements, for loop takes “14 seconds”, while list comprehension taks just about “9 seconds”. It is clear that for loop is much slower compared to list comprehension.
Computing Execution time with Jupyter Magic Functions %time and %timeit
Another option to compute execution time for your code is to use Jupyter’s magic functions %time and
%timeit. One of the advantages with using these magic functions is that we don’t have to load any module. We can use them straightaway. The magic function %time runs a statement once and gets total execution time.
>%%time >my_list=c[] >for i in range(1000000): my_list.append(i)
CPU times: user 143 ms, sys: 8.74 ms, total: 151 ms Wall time: 151 ms
Note that it gives the total time including system time.
>%%time >my_list=[i for i in range(1000000)]
CPU times: user 86.4 ms, sys: 8.71 ms, total: 95.1 ms Wall time: 94.2 ms
The magic function %timeit runs a statement multiple times and gets the best execution time. For a slower running code %timeit can adjust the number of times it gets execution time.
>%%timeit >my_list=c[] >for i in range(1000000): my_list.append(i)
10 loops, best of 3: 103 ms per loop
Note that it computes the execution time 10 times and reports the average time for the top 3 runs.
>%%timeit >my_list=[i for i in range(1000000)]
10 loops, best of 3: 57.3 ms per loop
To conclude, we have seen that for loop is slower than list comprehension when the number of elements is really high. They may perform very similar for a smaller list, so why don’t test it out with your favorite way to test execution time.