DEV Community

Cover image for How to make code faster in Python ? Some tips about make faster the code
Enes Karataş
Enes Karataş

Posted on

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
        pass
Enter fullscreen mode Exit fullscreen mode

and

    for i in range(100_000_000):
        pass
Enter fullscreen mode Exit fullscreen mode

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.

Syntax:

  • 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.

stmt:

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

setup:

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

timer:

  • 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:

  • 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
Enter fullscreen mode Exit fullscreen mode

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
         while(c<n):
             t += c
             c += 1
         return t
Enter fullscreen mode Exit fullscreen mode

The next one is main method in if scope:

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

and

     if __name__ == "__main__":
          main()
Enter fullscreen mode Exit fullscreen mode

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

     Output:
     while loop execution time =>     13.3874618
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
   Output:
   for loop execution time =>       7.5061377
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
     Output:
     for loop execution time =>       18.310060200000002
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode
    Output:
    sum method execution time =>       4.478143
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
     def numpy_arange_sum(n=100_000_000):
          return np.sum(np.arange(n))
Enter fullscreen mode Exit fullscreen mode

We get the following output.

   numpy sum and arange execution time =>         0.3317797
Enter fullscreen mode Exit fullscreen mode

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.

Sources

You can also find my github here.

Top comments (0)