When we become proficient in programming languages, we want to not only achieve the end goal, but also make our programs efficient.

In this tutorial, we’ll learn some Ipython commands that help us time analyze Python code.

Note that IN this tutorial, I recommend using Anaconda.

1. Analyze a line of code

To check the execution time of a line of Python code, use **%timeit**. Here’s a simple example to see how it works:

#### magics %timeit [num for num in range(20)] #### output 1.08 µs ± 43 ns per loop (mean ± std.dev.of 7) runs, 1000000 loops each)Copy the code

Main points for attention:

  • Use %timeit before the line to be parsed

  • It returns the average and standard deviation of the code run. In the example above, it is executed seven times, looping through the code one million times each time (the default behavior). This requires an average standard deviation of 1.08 microseconds and 43 nanoseconds.

  • When the MAGIC command is invoked, you can customize the number of runs and loops. The following is an example:

    Customize the number of runs and loops in %timeit magic command

    %timeit -r5 -n100 [num for num in range(20)]

    1.01 µs ± 5.75 ns per loop (mean ± std.dev. Of 5 runs, 100 loops each)

Using the command options -r and -n, which represent the number of executions and the number of loops respectively, we customized the time profile operation to execute 5 times and loop 100 times.

2. Analyze multiple lines of code

This section takes a step forward and explains how to analyze a complete code block. A complete code block can be parsed by making a small change to the %timeit Magic command, replacing a single percentage (%) with a double percentage (%%). The following is an example for your reference:

#### 使用timeblock%%代码分析
%%timeit -r5 -n1000
for i in range(10):
    n = i**2
    m = i**3
    o = abs(i)

#### 输出
10.5 µs ± 226 ns per loop (mean ± std. dev. of 5 runs, 1000 loops each)
Copy the code

You can observe that the average execution time of the for loop is 10.5 microseconds. Note that the command options -r and -n are used to control the number of executions and loops, respectively.

3. Time analysis for each line of code in the code block

So far, we have only looked at summary statistics when analyzing a line of code or a block of code. What if we wanted to evaluate the performance of each line of code in a code block? Use Line_profiler.

The Line_profiler package can be used to perform line-by-line analysis of any function. To use the Line_profiler package, perform the following steps:

  • Installation – The Line_profiler package can be installed by simply calling PIP or conda Install. If you are using the Anaconda distribution for Python, the conda installation is recommended

    Install the Line_profiler package

    conda install line_profiler

Load the extension – once installed, you can use IPython to load line_profiler:

#### loads line_profiler's Ipython extension %load_ext line_profiler1Copy the code

Time profiling functions – After loading, time profiling any predefined function using the following syntax

%lprun -f function_name_only function_call_with_arguments
Copy the code

Syntax details:

  • The call to line_profiler starts with the keyword %lprun, followed by the command option -f
  • The command option is followed by the function name, followed by the function call

In this exercise, we will define a function that takes a list of heights (in meters) and weights (in pounds) and converts them to centimeters and kilograms, respectively.

#### define function def conversion(ht_mtrs, wt_lbs): Ht_cms = [HT *100 for HT in ht_mtrs] wt_kgs = [wt*.4535 for wt in wt_lbs] #### Define height and weight list: Ht = [5,5,4,7,6] wt = [108, 120, 110, 98] #### use line_profiler analysis function %lprun -f conversion conversion(ht,wt) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - # # # # output Total time: 1.46 e-05 s File: <ipython-input-13-41e195af43a9> Function: conversion at line 2 Line # Hits Time Per Hit % Time Line Contents = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 2 1, 105.0 105.0 71.9 ht_cms = [ht * 100 for ht in ht_mtrs] 1 1 41.0 41.0 28.1 wt_kgs = [wt*.4535 for wt in wt_lbs]Copy the code

Output details:

In 14.6 microseconds (refer to first line output)

The generated table has 6 columns:

  • Column 1 (line #) – The line number of the code (note that line #1 is intentionally omitted from the output because it is just a function definition statement)
  • Column 2 (hit) – Number of times that line was called
  • Column 3 (Time) – Units of time spent on lines of code (14.6 microseconds per unit)
  • Column 4 (average time per hit) – column 3 divided by column 2
  • Column 5 (%Time) – What percentage of total Time is spent on a particular line of code
  • Column 6 (content) – the content of the line of code

You can clearly notice that the change in height from meters to centimeters takes up almost 72% of the time.

conclusion

With the execution time of each line of code, we can deploy strategies to improve the efficiency of our code. In the next three tutorials, we’ll share some best practices to help you make your code more efficient.

I hope this tutorial has been helpful and you’ve learned something new.

The original link: towardsdatascience.com/did-you-kno…

Source code point this get