【发布时间】:2013-03-19 21:15:39
【问题描述】:
我编写了 SSE 代码来汇总字节值。 (VS2005.)
因为它足够简单,所以效果很好(而且速度很快)。只有某些大小的数组会发生崩溃。它只在发布模式下崩溃 - 在调试中永远不会。也许有人看到了“明显”的错误? 任何帮助表示赞赏。
__int64 Sum (const unsigned char* pData, const unsigned int& nLength)
{
__int64 nSum (0);
__m128i* pp = (__m128i*)pData;
ATLASSERT( ( (DWORD)pp & 15 ) == 0 ); // pointer must point to address multiple of 16 (cache line)
__m128i zero = _mm_setzero_si128(),
a, b, c, d, tmp;
unsigned int i (0);
for ( ; i < nLength; i+=64) // 4-fach loop-unroll (x 16)
{
a = _mm_sad_epu8( *(pp++), zero);
b = _mm_sad_epu8( *(pp++), zero); // It crashes here.
c = _mm_sad_epu8( *(pp++), zero);
d = _mm_sad_epu8( *(pp++), zero);
// commenting the following line prevents the crash (???)
tmp = _mm_add_epi64( _mm_add_epi64( _mm_add_epi64( a, b ), c ), d);
a = _mm_srli_si128 ( tmp, 8 );
nSum += _mm_cvtsi128_si32( a ) + _mm_cvtsi128_si32( tmp );
}
// ... the rest
if (nLength % 64)
for (i -= 64; i < nLength; i++)
nSum += pData [i];
return nSum;
}
函数是这样调用的:
unsigned int nLength = 3571653; // One of the values that causes crash
unsigned char *pData = (unsigned char*) _aligned_malloc(nLength, 16);
Sum (pData, nLength);
【问题讨论】:
-
嗯,你检查过
pp还在范围内吗? -
检查调试和发布模式之间的程序集差异,因为发布模式优化可能破坏了您所做的假设。
-
这对其他人来说是不是过早的优化?
-
@modifiablelvalue no?
-
@harold 编译器可能会自动为你做这件事吗?即使在没有自动完成优化的情况下,总结一组
unsigned shorts 似乎太可能成为瓶颈?这对缓存很友好;也许还有其他对缓存不太友好的领域值得更高优先级关注;)
标签: c algorithm visual-studio-2005 sse