以下是我划分两个矩阵的代码:
def divideM1(X,Y):
n=len(X)
a=[[col for col in row[:len(row)/2]] for row in X[:n/2]]
b=[[col for col in row[len(row)/2:]] for row in X[:n/2]]
c=[[col for col in row[:len(row)/2]] for row in X[n/2:]]
d=[[col for col in row[len(row)/2:]] for row in X[n/2:]]
e=[[col for col in row[:len(row)/2]] for row in Y[:n/2]]
f=[[col for col in row[len(row)/2:]] for row in Y[:n/2]]
g=[[col for col in row[:len(row)/2]] for row in Y[n/2:]]
h=[[col for col in row[len(row)/2:]] for row in Y[n/2:]]
return a,b,c,d,e,f,g,h
def divideM2(X,Y):
n=len(X)
a=[[0 for i in range(n/2)] for j in range(n/2)]
b=[[0 for i in range(n/2)] for j in range(n/2)]
c=[[0 for i in range(n/2)] for j in range(n/2)]
d=[[0 for i in range(n/2)] for j in range(n/2)]
f=[[0 for i in range(n/2)] for j in range(n/2)]
e=[[0 for i in range(n/2)] for j in range(n/2)]
g=[[0 for i in range(n/2)] for j in range(n/2)]
h=[[0 for i in range(n/2)] for j in range(n/2)]
for i in range(n/2):
for j in range(n/2):
a[i][j]=X[i][j]
b[i][j]=X[i][j+n/2]
c[i][j]=X[i+n/2][j]
d[i][j]=X[i+n/2][j+n/2]
e[i][j]=Y[i][j]
f[i][j]=Y[i][j+n/2]
g[i][j]=Y[i+n/2][j]
h[i][j]=Y[i+n/2][j+n/2]
return a,b,c,d,e,f,g,h
如果我使用time.time(),似乎方法2-“divideM2”比方法1更快 - “divideM1”,但为什么呢? 是否有更好的划分方法?
EDIT1: 有趣的是,当我使用time.time()时:
start = time.time()
print("method1")
for i in range(10000):
1>2
divideM2(a1,a1)
end = time.time()
t1=end-start
print t1 ,"m1"
start = time.time()
print("method2")
for j in range(10000):
1>2
divideM1(a2,a2)
end = time.time()
t2= end-start
print t2, "m2"
if t1>t2:
print "method 2 is faster"
else:
print "method 1 is faster"
即使我自己比较“divide1”,我总是得到“方法2更快”。有人可以解释一下吗?