在比较Android上SL4A的较长(> 1行)代码段时,我使用timeit()作为准确的基准测试时遇到了一些问题。比较时间时,我的变化非常大。 (可能与android / dalvik vm分配cpu时间的方式有关吗?)。
无论如何,我写了一个脚本,它使用假设检验来分析大(~1000)次样本。这种方法有什么问题吗?
from math import sqrt
import timeit
#statistics stuff
mean = lambda x: sum(x) / float(len(x))
def stdev (mean, dataset):
variance = ((x - mean)**2 for x in dataset)
deviation = sqrt(sum(variance) / float(len(dataset) - 1))
return deviation / sqrt(len(dataset))
def interval(mean, sampleDeviation, defaultZ = 1.57):
margin = sampleDeviation * defaultZ
return (mean - margin, mean + margin)
def testnull(dataset1, dataset2, defaultZ = 1.57):
mean1, mean2 = mean(dataset1), mean(dataset2)
sd1, sd2 = stdev(mean1, dataset1), stdev(mean2, dataset2)
interval1, interval2 = interval(mean1, sd1, defaultZ), interval(mean2, sd2, defaultZ)
inside = lambda x, y: y >= x[0] and y <= x[1]
if inside(interval1, interval2[0]) or inside(interval1, interval2[1]):
return True
return False
#timer setup
t1 = timeit.Timer('sum(x)', 'x = (i for i in range(1000))')
t2 = timeit.Timer('sum(x)', 'x = list(range(1000))')
genData, listData = [], []
for i in range(10000):
genData.append(t1.timeit())
listData.append(t2.timeit())
# testing the interval
print('The null hypothesis is {0}'.format(testnull(genData, listData)))