Performance measure of a python code

Posted by

Measure perfomance of Python code:

There are multiple way to measure performance of a python code, one of  them is using perf_counter method of time module.

The perf_counter method returns the time measured in nano second.

Triplet Sum function using for loop and while loop:

def find_triplets(nums, target):

triplets = []

nums.sort() # Sort the list for efficient two-pointer approach

for i in range(len(nums) - 2):

# Skip duplicates for the first element

if i > 0and nums[i] == nums[i - 1]:

continue

left = i + 1

right = len(nums) - 1

while left < right:

total = nums[i] + nums[left] + nums[right]

if total == target:

triplets.append([nums[i], nums[left], nums[right]])

# Skip duplicates for the second and third elements

while left < right and nums[left] == nums[left + 1]:

left += 1

while left < right and nums[right] == nums[right - 1]:

right -= 1

left += 1

right -= 1

elif total < target:

left += 1

else:

right -= 1

return triplets

Triplet sum function using Itertools:

def find_triplets(numbers,target):

listCombinations = list(combinations(numbers,3))

temp = []

for item in listCombinations:

if sum(item) == target:

temp.append(item)

return temp
Full Code :
import time

from itertools import combinations

import random

## paste find tripet either of the function here



myList = random.sample(range(0,200),80)

target = 60

t1 = time.perf_counter()

print(find_triplets(myList,target))

t2 = time.perf_counter()

print(f"time taken --->{t2-t1}")
Conclusion:
Using perf_counter method we can measure how much time a python code has taken to complete its jobs.

Leave a Reply

Your email address will not be published. Required fields are marked *