相关疑难解决方法(0)

C++的新操作是否保证地址返回的对齐?

大多数有经验的程序员都知道数据对齐对于程序的性能很重要.我看到一些程序员编写的程序分配比他们需要的更大的缓冲区大小,并使用对齐的指针作为开始.我想知道我应该在我的程序中这样做,我不知道是否有任何保证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)

c++ performance alignment new-operator

28
推荐指数
5
解决办法
2万
查看次数

用新的回归对齐的记忆?

我目前使用MS特定的mm_malloc为阵列分配内存.我调整了内存,因为我正在做一些重型数学运算,矢量化利用了对齐.我想知道是否有人知道如何重载新操作符来做同样的事情,因为我觉得到处都是脏的malloc'ing(最终还想在Linux上编译)?谢谢你的帮助

c++ alignment

8
推荐指数
1
解决办法
1万
查看次数

按位运算.这段代码安全且便携吗?

我需要计算表示为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)

c++

7
推荐指数
1
解决办法
502
查看次数

标签 统计

c++ ×3

alignment ×2

new-operator ×1

performance ×1