我有一些简单的代码可以执行以下操作。
它迭代所有可能的长度n列表F
,带有+ -1个条目。对于每一个,它迭代所有可能的长度2n
列表S
,带有+ -1个条目,其中$ S $的前半部分只是下半部分的副本。该代码计算F
的内积,其中S
的每个子列表的长度为n
。对于每个F,S,它计算在第一个非零内积之前为零的内积。
这是代码。
#!/usr/bin/python
from __future__ import division
import itertools
import operator
import math
n=14
m=n+1
def innerproduct(A, B):
assert (len(A) == len(B))
s = 0
for k in xrange(0,n):
s+=A[k]*B[k]
return s
leadingzerocounts = [0]*m
for S in itertools.product([-1,1], repeat = n):
S1 = S + S
for F in itertools.product([-1,1], repeat = n):
i = 0
while (i<m):
ip = innerproduct(F, S1[i:i+n])
if (ip == 0):
leadingzerocounts[i] +=1
i+=1
else:
break
print leadingzerocounts
n=14
的正确输出是
[56229888, 23557248, 9903104, 4160640, 1758240, 755392, 344800, 172320, 101312, 75776, 65696, 61216, 59200, 59200, 59200]
使用pypy,n = 14需要1分18秒。不幸的是,我真的想为16,18,20,22,24,26运行它。我不介意使用numba或cython但是如果可能的话我想保持接近python。
非常感谢任何加快这一进程的帮助。
我会在这里记录最快的解决方案。 (如果我错过了更新的答案,请告诉我。)
答案 0 :(得分:22)
通过利用问题的循环对称性,这个新代码获得了另一个数量级的加速。这个Python版本使用Duval的算法枚举项链; C版本使用蛮力。两者都包含下面描述的加速。 在我的机器上,C版本在100秒内解决了n = 20!一个封装计算表明,如果你让它在一个核心上运行一周,它就会可以做n = 26,并且,如下所述,它适合于并行性。
import itertools
def necklaces_with_multiplicity(n):
assert isinstance(n, int)
assert n > 0
w = [1] * n
i = 1
while True:
if n % i == 0:
s = sum(w)
if s > 0:
yield (tuple(w), i * 2)
elif s == 0:
yield (tuple(w), i)
i = n - 1
while w[i] == -1:
if i == 0:
return
i -= 1
w[i] = -1
i += 1
for j in range(n - i):
w[i + j] = w[j]
def leading_zero_counts(n):
assert isinstance(n, int)
assert n > 0
assert n % 2 == 0
counts = [0] * n
necklaces = list(necklaces_with_multiplicity(n))
for combo in itertools.combinations(range(n - 1), n // 2):
for v, multiplicity in necklaces:
w = list(v)
for j in combo:
w[j] *= -1
for i in range(n):
counts[i] += multiplicity * 2
product = 0
for j in range(n):
product += v[j - (i + 1)] * w[j]
if product != 0:
break
return counts
if __name__ == '__main__':
print(leading_zero_counts(12))
C版:
#include <stdio.h>
enum {
N = 14
};
struct Necklace {
unsigned int v;
int multiplicity;
};
static struct Necklace g_necklace[1 << (N - 1)];
static int g_necklace_count;
static void initialize_necklace(void) {
g_necklace_count = 0;
for (unsigned int v = 0; v < (1U << (N - 1)); v++) {
int multiplicity;
unsigned int w = v;
for (multiplicity = 2; multiplicity < 2 * N; multiplicity += 2) {
w = ((w & 1) << (N - 1)) | (w >> 1);
unsigned int x = w ^ ((1U << N) - 1);
if (w < v || x < v) goto nope;
if (w == v || x == v) break;
}
g_necklace[g_necklace_count].v = v;
g_necklace[g_necklace_count].multiplicity = multiplicity;
g_necklace_count++;
nope:
;
}
}
int main(void) {
initialize_necklace();
long long leading_zero_count[N + 1];
for (int i = 0; i < N + 1; i++) leading_zero_count[i] = 0;
for (unsigned int v_xor_w = 0; v_xor_w < (1U << (N - 1)); v_xor_w++) {
if (__builtin_popcount(v_xor_w) != N / 2) continue;
for (int k = 0; k < g_necklace_count; k++) {
unsigned int v = g_necklace[k].v;
unsigned int w = v ^ v_xor_w;
for (int i = 0; i < N + 1; i++) {
leading_zero_count[i] += g_necklace[k].multiplicity;
w = ((w & 1) << (N - 1)) | (w >> 1);
if (__builtin_popcount(v ^ w) != N / 2) break;
}
}
}
for (int i = 0; i < N + 1; i++) {
printf(" %lld", 2 * leading_zero_count[i]);
}
putchar('\n');
return 0;
}
你可以通过利用符号对称性(4x)和迭代那些通过第一个内积测试的向量(渐近,O(sqrt(n))x)来获得一点加速。
import itertools
n = 10
m = n + 1
def innerproduct(A, B):
s = 0
for k in range(n):
s += A[k] * B[k]
return s
leadingzerocounts = [0] * m
for S in itertools.product([-1, 1], repeat=n - 1):
S1 = S + (1,)
S1S1 = S1 * 2
for C in itertools.combinations(range(n - 1), n // 2):
F = list(S1)
for i in C:
F[i] *= -1
leadingzerocounts[0] += 4
for i in range(1, m):
if innerproduct(F, S1S1[i:i + n]):
break
leadingzerocounts[i] += 4
print(leadingzerocounts)
C版,了解我们输给PyPy的性能有多少(PyPy为16,C大致相当于18):
#include <stdio.h>
enum {
HALFN = 9,
N = 2 * HALFN
};
int main(void) {
long long lzc[N + 1];
for (int i = 0; i < N + 1; i++) lzc[i] = 0;
unsigned int xor = 1 << (N - 1);
while (xor-- > 0) {
if (__builtin_popcount(xor) != HALFN) continue;
unsigned int s = 1 << (N - 1);
while (s-- > 0) {
lzc[0]++;
unsigned int f = xor ^ s;
for (int i = 1; i < N + 1; i++) {
f = ((f & 1) << (N - 1)) | (f >> 1);
if (__builtin_popcount(f ^ s) != HALFN) break;
lzc[i]++;
}
}
}
for (int i = 0; i < N + 1; i++) printf(" %lld", 4 * lzc[i]);
putchar('\n');
return 0;
}
这个算法令人尴尬地并行,因为它只是累积xor
的所有值。对于C版本,一个背后的计算表明,几千小时的CPU时间足以计算n = 26
,这在EC2上以当前的速率计算为几百美元。毫无疑问会有一些优化(例如,矢量化),但对于像这样的一次性,我不确定程序员的努力程度是多少值得的。
答案 1 :(得分:7)
n的一个非常简单的加速因素是更改此代码:
def innerproduct(A, B):
assert (len(A) == len(B))
for j in xrange(len(A)):
s = 0
for k in xrange(0,n):
s+=A[k]*B[k]
return s
到
def innerproduct(A, B):
assert (len(A) == len(B))
s = 0
for k in xrange(0,n):
s+=A[k]*B[k]
return s
(我不知道为什么你的循环超过j,但它每次只进行相同的计算,所以不需要。)
答案 2 :(得分:2)
我已经将其转移到NumPy数组并借用了这个问题:itertools product speed up
这就是我所拥有的,(这里可能会有更多的加速):
def find_leading_zeros(n):
if n % 2:
return numpy.zeros(n)
m = n+1
leading_zero_counts = numpy.zeros(m)
product_list = [-1, 1]
repeat = n
s = (numpy.array(product_list)[numpy.rollaxis(numpy.indices((len(product_list),) * repeat),
0, repeat + 1).reshape(-1, repeat)]).astype('int8')
i = 0
size = s.shape[0] / 2
products = numpy.zeros((size, size), dtype=bool)
while i < m:
products += (numpy.tensordot(s[0:size, 0:size],
numpy.roll(s, i, axis=1)[0:size, 0:size],
axes=(-1,-1))).astype('bool')
leading_zero_counts[i] = (products.size - numpy.sum(products)) * 4
i += 1
return leading_zero_counts
为n = 14跑步我得到:
>>> find_leading_zeros(14)
array([ 56229888., 23557248., 9903104., 4160640., 1758240.,
755392., 344800., 172320., 101312., 75776.,
65696., 61216., 59200., 59200., 59200.])
所以一切看起来都不错。至于速度:
>>> timeit.timeit("find_leading_zeros_old(10)", number=10)
28.775046825408936
>>> timeit.timeit("find_leading_zeros(10)", number=10)
2.236745834350586
看看你的想法。
编辑:
原始版本为N = 14使用了2074MB的内存,因此我删除了连接数组并改为使用numpy.roll
。同时更改数据类型以使用布尔数组,n = 14时内存减少到277MB。
时间方面,编辑再次快一点:
>>> timeit.timeit("find_leading_zeros(10)", number=10)
1.3816070556640625
EDIT2:
好的,所以加入David所指出的对称性,我再次减少了这一点。它现在使用213MB。比较时间与之前的编辑相比:
>>> timeit.timeit("find_leading_zeros(10)", number=10)
0.35357093811035156
我现在可以在14秒内在我的Mac书上做n = 14的情况,这对于&#34;纯粹的python&#34;我想。
答案 3 :(得分:2)
我试图加快速度,但我失败了:(
但是我发送代码时,它的速度更快,但对于像n=24
这样的值来说还不够快。
我的假设
您的列表由值组成,因此我决定使用数字而不是列表 - 每个位代表一个可能的值:如果设置了位,则表示1
,如果它被归零则意味着-1
。乘法{-1, 1}
的唯一可能结果是1
或-1
,因此我使用按位XOR
而不是乘法。我还注意到它有一个对称性,所以你只需要检查可能列表的子集(四分之一)并将结果乘以4(David在他的回答中解释了这一点)。
最后,我将可能的操作结果放到表中,以消除计算需求。它需要大量的内存,但是谁在乎(对于n=24
它大概是150MB)?
然后@David Eisenstat回答了这个问题:)
所以,我把他的代码修改为基于位的。它大约快2-3倍(n=16
花了大约30秒,相比大卫的解决方案大约90,但我认为它还不够n=26
左右的结果。
import itertools
n = 16
m = n + 1
mask = (2 ** n) - 1
# Create table of sum results (replaces innerproduct())
tab = []
for a in range(2 ** n):
s = 0
for k in range(n):
s += -1 if a & 1 else 1
a >>= 1
tab.append(s)
# Create combination bit masks for combinations
comb = []
for C in itertools.combinations(range(n - 1), n // 2):
xor = 0
for i in C:
xor |= (1 << i)
comb.append(xor)
leadingzerocounts = [0] * m
for S in xrange(2 ** (n-1)):
S1 = S + (1 << (n-1))
S1S1 = S1 + (S1 << n)
for xor in comb:
F = S1 ^ xor
leadingzerocounts[0] += 4
for i in range(1, m):
if tab[F ^ ((S1S1 >> i) & mask)]:
break
leadingzerocounts[i] += 4
print(leadingzerocounts)
<强>结论强>
我以为我发明了一些非常出色的东西,并希望所有这些混乱的东西都能提供极大的速度提升,但是这种提升令人失望地小:(
我认为原因是Python使用运算符的方式 - 它为每个算术(或逻辑)运算调用函数,即使它可以通过单个汇编程序命令完成(我希望pypy
能够简化运算到那个级别,但它没有。所以,如果C(或ASM)与这个位操作解决方案一起使用,它可能会表现很好(也许你可以进入n=24
)。
答案 4 :(得分:0)
在我看来,提高性能的一个好方法是使用python builtins。
首先使用map来计算条目的乘积:
>>> a =[1,2,3]
>>> b = [4,5,6]
>>>map(lambda x,y : x*y, a , b)
[4, 10, 18]
然后使用reduce计算总和:
>>> reduce(lambda v,w: v+w, map(lambda x,y :x*y, a, b))
32
那么你的功能就变成了
def innerproduct(A, B):
assert (len(A) == len(B))
return reduce(lambda v,w: v+w, map(lambda x,y :x*y, A, B))
接下来,我们可以采取所有这些&#34; for循环&#34; out并用生成器替换它们并捕获StopIteration。
#!/usr/bin/python
from __future__ import division
import itertools
import operator
import math
n=14
m=n+1
def innerproduct(A, B):
assert (len(A) == len(B))
return reduce(lambda v,w: v+w, map(lambda x,y :x*y, A, B))
leadingzerocounts = [0]*m
S_gen = itertools.product([-1,1], repeat = n)
try:
while(True):
S = S_gen.next()
S1 = S + S
F_gen = itertools.product([-1,1], repeat = n)
try:
while(True):
F = F_gen.next()
for i in xrange(m):
ip = innerproduct(F, S1[i:i+n])
if (ip == 0):
leadingzerocounts[i] +=1
i+=1
else:
break
except StopIteration:
pass
except StopIteration as e:
print e
print leadingzerocounts
我观察到较小的n加速,但我的jalopy缺乏计算我的版本的马力,也没有n = 14的原始代码。进一步提高速度的一种方法是记住这一行:
F_gen = itertools.product([-1,1], repeat = n)