I was trying to compare the efficiency of the if statement compared to initialization of a loop in two basic code snippets where one snippet first compares the values first using if statement and then uses a while loop and the other snippet directly uses while loop to check statement. Using the code :
import time
def snippet1(nums):
nums.sort()
c = 0
for i in range(1, len(nums)):
if nums[i] <= nums[i-1]:
while nums[i] <= nums[i-1]:
nums[i] += 1
c += 1
return c
def snippet2(nums):
nums.sort()
c = 0
for i in range(1, len(nums)):
while nums[i] <= nums[i-1]:
nums[i] += 1
c += 1
return c
# Sample list of numbers
nums = [5, 1, 3, 2, 4, 2, 1, 6, 5, 8, 9, 7, 3, 2, 5]
# Measure time for snippet1
start_time = time.time()
snippet1(nums)
end_time = time.time()
print("Time for snippet1:", end_time - start_time)
# Measure time for snippet2
start_time = time.time()
snippet2(nums)
end_time = time.time()
print("Time for snippet2:", end_time - start_time)
Though the results were as estimated, the result became weird when I changed “nums[:]” to “nums” in the driver code. The only effect was on the result time of snippet2 where when using nums[:] the avg time was 1.5 seconds and with nums it became 5 seconds whereas time of snippet1 remained the same in both cases with avg of 2s.
It doesn’t makes sense to me how passing a array copy or passing a array reference affects only the if statement?
Result with nums[:]:
Time for snippet1: 1.52587890625e-05
Time for snippet2: 1.430511474609375e-05
=== Code Execution Successful ===
Result with nums:
Time for snippet1: 2.0265579223632812e-05
Time for snippet2: 5.245208740234375e-06
=== Code Execution Successful ===
Hassan Mustafa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.