场景:
1. 有些频繁使用的指针变量地址不对齐的话运行效率和对齐后的运行效率差别很大,所以在创建堆空间时,有必要对内存地址对齐提高运行效率.
2. 有些音视频处理的代码或者说自定义的malloc基本都是地址对齐的.
3. 使用原子访问的互锁函数时,InterlockedExchangeAdd都需要地址对齐.
4. 主要还是宏APR_ALIGN, 这个说是Apache源码里,就借用一下吧。
解决方案:
1. 其实就是让地址值对对齐量求模为0, 地址值最多增加n-1个偏移地址就可就可以整出n. &~(n-1)就是能整除n的快捷方法,相当于左移2的倍数位.
#include <iostream>
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
using namespace std;
// Apache
/* APR_ALIGN() is only to be used to align on a power of 2 boundary */
#define APR_ALIGN(size, boundary) (((size) + ((boundary) - 1)) & ~((boundary) - 1))
void TestAlgin()
{
//1. 32字节对齐. 数值地址.要对齐地址,一般会创建多出的空间来对齐.
//1. 需要创建16字节空间,如果需要32字节对齐.
uint8_t* value = (uint8_t*)malloc(16+32);
cout <<"1 " << (int64_t)(int64_t*)(value) << endl;
int64_t* value_offset = (int64_t*)APR_ALIGN((int64_t)(int64_t*)value,32);
cout <<"2 " << (int64_t)(int64_t*)(value_offset) << endl;
//1. 测试自定义4字节对齐,源地址是5,最终地址是8.
int64_t v1 = APR_ALIGN(5,sizeof(int32_t));
assert(v1 == 8);
//1. 测试自定义8字节对齐,原地址是10,最终地址是16
v1 = APR_ALIGN(10,sizeof(int64_t));
assert(v1 == 16);
}
int main(int argc, char const *argv[])
{
TestAlgin();
return 0;
}输出:
1 6314480 2 6314496
参考:
http://bbs.csdn.net/topics/370085011
http://bbs.chinaunix.net/thread-1233919-1-1.html
《Windows核心编程 第4版》
原文地址:http://blog.csdn.net/infoworld/article/details/43972449