大多数有经验的程序员都知道数据对齐对于程序的性能很重要.我看到一些程序员编写的程序分配比他们需要的更大的缓冲区大小,并使用对齐的指针作为开始.我想知道我应该在我的程序中这样做,我不知道是否有任何保证C++的新操作返回的地址对齐.所以我写了一个小程序来测试
for(size_t i = 0; i < 100; ++i) {
char *p = new char[123];
if(reinterpret_cast<size_t>(p) % 4) {
cout << "*";
system("pause");
}
cout << reinterpret_cast<void *>(p) << endl;
}
for(size_t i = 0; i < 100; ++i) {
short *p = new short[123];
if(reinterpret_cast<size_t>(p) % 4) {
cout << "*";
system("pause");
}
cout << reinterpret_cast<void *>(p) << endl;
}
for(size_t i = 0; i < 100; ++i) {
float *p = new float[123];
if(reinterpret_cast<size_t>(p) % 4) {
cout …Run Code Online (Sandbox Code Playgroud) 我目前使用MS特定的mm_malloc为阵列分配内存.我调整了内存,因为我正在做一些重型数学运算,矢量化利用了对齐.我想知道是否有人知道如何重载新操作符来做同样的事情,因为我觉得到处都是脏的malloc'ing(最终还想在Linux上编译)?谢谢你的帮助
我需要计算表示为char数组的位集之间的汉明距离.这是一项核心操作,因此必须尽可能快.我有这样的事情:
const int N = 32; // 32 always
// returns the number of bits that are ones in a char
int countOnes_uchar8(unsigned char v);
// pa and pb point to arrays of N items
int hamming(const unsigned char *pa, const unsigned char *pb)
{
int ret = 0;
for(int i = 0; i < N; ++i, ++pa, ++pb)
{
ret += countOnes_uchar8(*pa ^ *pb);
}
return ret;
}
Run Code Online (Sandbox Code Playgroud)
在分析之后,我注意到在ints上运行更快,所以我写道:
const int N = 32; // …Run Code Online (Sandbox Code Playgroud)