In Python, we can time our code using the %timeit magic command in Jupyter notebooks or the timeit module in regular Python scripts. Here's how to use %timeit:
-
In a Jupyter notebook, simply prepend
%timeitto the line of code you want to time. For example:%timeit x = 1 + 2This will time how long it takes to execute the statement
x = 1 + 2and print the results. -
In a regular Python script, you can use the
timeitmodule to time your code. Here's an example:import timeitdef my_function():x = 1 + 2print(timeit.timeit(my_function, number=100000))This code defines a function
my_functionthat simply adds 1 and 2 together, and then times how long it takes to execute the function 100,000 times using thetimeit.timeitfunction. Thenumberparameter specifies how many times to execute the code. The result is printed to the console.
Both %timeit and timeit.timeit run the code multiple times and return the average execution time. This helps to ensure that the timing results are accurate and not skewed by variations in system load or other factors.
By using %timeit and timeit.timeit, we can easily time our code and get accurate performance measurements. This information can be used to optimize our code and improve its performance.