Pages

Tuesday, 9 August 2022

How to make python code run faster ?

 Use Built-in Functions

#Slow: start = time.time() new_list = [] for word in word_list: new_list.append(word.capitalize()) print(time.time() - start, "seconds")

 4.935264587402344e-05 seconds

#fast  
start = time.time() 
word_list = ['Ways', 'to', 'Make', 'Your', 'Python', 'Code', 'Faster'] new_list = list(map(str.capitalize, word_list))  
print(time.time() - start, "seconds") 

0.00029468536376953125 seconds


String Concatenation vs join()

#Slow: 
start = time.time() 

new_list = [] for 
word in word_list:     
new_list += word 
     
print(time.time() - start, "seconds")

 5.7220458984375e-05 seconds

#fast
start = time.time() 
 
word_list = ['Ways', 'to', 'Make', 'Your', 'Python', 'Code', 'Faster']
new_list = "".join(word_list)
 
print(time.time() - start, "seconds") 

0.0001430511474609375 seconds


Create List and Dictionaries Faster

   
#slow  
list() 
dict() 
Output:
{}

#fast  
() 
{} 

Output:
{} 

Example : 

import timeit 
slower_list = timeit.timeit("list()", number=10**6) 
slower_dict = timeit.timeit("dict()", number=10**6) 
 
faster_list = timeit.timeit("[]", number=10**6)
faster_dict = timeit.timeit("{}", number=10**6) 

print("slower_list:",slower_list, "sec")  #Should have used f string here..
print("slower_dict:",slower_dict, "sec")
print("faster_list:",faster_list, "sec")
print("faster_dict:",faster_dict, "sec")

slower_list: 0.03651356499995018 sec
slower_dict: 0.047055111999952715 sec
faster_list: 0.010666104999927484 sec
faster_dict: 0.010838708999926894 sec 


 Use f-Strings

#slow
start = time.time() 
 
me = "Python" 
string = "Make " + me + " faster" 
 
print(time.time() - start, "seconds") 


 4.506111145019531e-05 seconds


#fast
start = time.time() 
 
me = "Python" 
string = f"Make {me} faster" 
 
print(time.time() - start, "seconds") 

 0.00016546249389648438 seconds


List Comprehensions

#slow
start = time.time() 
new_list = [] 
existing_list = range(1000000) for i in existing_list: 
    if i % 2 == 1: 
        new_list.append(i) 
         
print(time.time() - start, "seconds") 

 0.06872344017028809 seconds

#fast
start = time.time() 
 
existing_list = range(1000000) 
new_list = [i for i in existing_list if i % 2 == 1] 
 
print(time.time() - start, "seconds")    

 0.04211759567260742 seconds


For more built-in functions, refer below url

https://docs.python.org/3/library/functions.html



#python #tips #codingstandards #code #optimized #fast #bestpractices #best #practices

No comments: