How to make code faster in Python ? Some tips about make faster the code

Step 1: Why do we need fast code ?

Sometimes we want the codes to run fast however it is not possible without clean codes. In this tutorial we are going to see how to make codes useful and compare them each other.

It is not only speed that matters here. We should determine the system requirements of the code by the system that will work on it. At this point we need to reduce the cost of the program for hardware and make faster.

Alright, suppose that there are two loops which iterate 100_000_000 times as follows:

i = 0
    while i < 100_000_000:
        i += 1


for i in range(100_000_000):

These codes do nothing as well so, their logics are the same. The execution time would be different so that one of them is while the other for loop. Of course it depends on its place of use in the program. So we are going to compare their execution time in the both while loop and for loop. So that we need a python method to do that. This is 'timeit' library. Let's look at how timeit works.

Step 2: Timeit Method

In this section we are going to see how to measure execution time of the functions and also discuss on that times.

The first let's look at the timeit. Surely I am going to begin with that question, What is the timeit ?
Timeit is a method in Python that provides a way to measure execution time of the functions. So we need to use this method when we want to get execution time of any function and also to check performance of codes. That means the execution time can be very important to refactoring and clean code.
Big projects consist of the small functions and methods so that either CPU or RAM cost of the functions should be
optimal to efficient use.
Let's figure out the syntax of timeit.


  • timeit.timeit(stmt, setup, timer, number)

There are various parameters that passed to timeit method above. We are going to investigate each other step by step.

Let's have a look at the parameters.


  • The parameter takes the code which you have defined before. The default is 'pass'.


  • Statement setup details to be executed before running the stmt. The default is 'pass'.


  • The parameter takes timer value as a default timer. Note that we will pass this parameter so, the number and stmt are what we need in this tutorial.


  • Number is the number of the execution number of the code which you defined as stmt.

So far so good !

Now we need to learn how to use timeit in python. Let's start exploring to code of the method. To work with timeit
we need to import that method. The first let me show how to import timeit.

As shown below we import like that:

import timeit

So, in the following example a while loop is defined in a function that called as while_loop. The function returns sum of numbers up to 100,000,000

def while_loop(n=100_000_000):
         c = 0
         t = 0
             t += c
             c += 1
         return t

The next one is main method in if scope:

def main():
          print("while loop execution time => \t",  
                      timeit.timeit(while_loop, number=1))


if __name__ == "__main__":

Finally end of the code ! We probably would get this output.

     while loop execution time =>     13.3874618

Alright, the CPU model is Intel Core i5 3337U on the PC. If you use better one then you can see less time. What if you have the same thing in for loop?

def for_loop(n=100_000_000):
          s = 0
          for i in range(0, n):
               s += i

          return s
   for loop execution time =>       7.5061377

Quite easy to explain this difference between while and for loop. It's range method. The range() function is written for python so that provides quite speed to loop. Suppose we check again the number n and increase c that inside of for loop.

def for_loop_with_check_and_inc(n=100_000_000):
          t = 0
          c = 0
     for _ in range(0, n):

          if _ < n :
              c += 1
              t += _
     return t
     for loop execution time =>       18.310060200000002

As you see if statement inside of the loop makes slow quite the code.
Alright let's do something else now. We are going to range() sequence again however inside of the sum() method. We now that before the range() provides immutable number sequence so that if we use range inside of the sum we probably are going get the sum of each number.

def sum_range_without_loop(n=100_000_000):
         return sum(range(n))
    sum method execution time =>       4.478143

What a huge difference according to for or while loops! Output is execution time of the sum of the first 100,000,000 number I mean the same with before functions but look at this difference.
Alright there is another way to use number sequence like range this is numpy.arange(). And we would also use numpy.sum method instead of the sum(). Before using this method we need to import numpy.

import numpy as np
def numpy_arange_sum(n=100_000_000):
          return np.sum(np.arange(n))

We get the following output.

numpy sum and arange execution time =>         0.3317797

The best time of all ! So, the whole features of numpy library are written in C language so that provides more efficient ram usage and executes so quick.

Finally, the module is used for to find out execution time of small codes. If you intend to use timeit just import module firstly. Thats sufficent to use module. Note that in different systems that have distinct hardware the time results will be different.

To more information please go to link below.


You can also find my github here.