Action 1: Multiplication of a random number a with another random number b Action 2: Multiplication of the same number a with 0
我进行了小规模试验,看看其中哪些行动的执行时间最小。 因此,我写了下文的小方案,即行动1,大量时间衡量其全部执行时间,并重复行动2,看看两者间执行时间最小的情况。 我重复了上述100次,以产生更可靠的结果。
执行该方案,以发现出于某种原因,行动1在大部分时间(约75%)中加快行动2。 对类似情况的解释是什么?
import time
import numpy as np
def compare_execution_times(a, b):
# Measure the execution time of multiplication with non-zero b
start_time = time.time()
for _ in range(1000000): # Perform multiplication a large number of times
result = a * b
end_time = time.time()
first_execution_time = end_time - start_time
# Measure the execution time of multiplication with zero b
start_time = time.time()
for _ in range(1000000): # Perform multiplication a large number of times
result = a * 0
end_time = time.time()
second_execution_time = end_time - start_time
return first_execution_time < second_execution_time
count_true = 0
count_false = 0
for _ in range(100):
a = np.random.rand() # Generate random a
b = np.random.rand() # Generate random b
if compare_execution_times(a, b):
count_true += 1
else:
count_false += 1
print("
Number of times first execution was smaller:", count_true)
print("Number of times second execution was smaller:", count_false)