Skip to content

Instantly share code, notes, and snippets.

@hansrajdas
Created January 27, 2023 19:55
Show Gist options
  • Save hansrajdas/48688904a5de8c6675b3df43a1edb792 to your computer and use it in GitHub Desktop.
Save hansrajdas/48688904a5de8c6675b3df43a1edb792 to your computer and use it in GitHub Desktop.
Python inbuilt functions are faster/optimized

Python inbuilt functions are faster/optimized

Taken a simple example: Generate a list 100 million number then sum them all using below 2 ways

First, using python's sum function on list

s = [i for i in range(100000000)]
f = sum(s)
print(f)
  • Run above code with measuring time
/tmp $ time python t1.py
4999999950000000

real	0m5.920s
user	0m4.820s
sys	0m1.085s

Second, looping over all number and adding them

s = [i for i in range(100000000)]
f = 0
for n in s:
    f += n
print(f)
  • Run above code measuring time
/tmp $ time python t2.py
4999999950000000

real	0m11.419s
user	0m10.304s
sys	0m1.101s

Takeway

After running multiple iterations also, first program which uses python built in function sum to find sum of all elements in list executes faster than second one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment