假設是這樣的:是否有標準的宏來檢測需要對齊內存訪問的體系結構?
void mask_bytes(unsigned char* dest, unsigned char* src, unsigned char* mask, unsigned int len)
{
unsigned int i;
unsigned int wordlen = len >> 2;
for(i=0; i<wordlen; i++)
{
((uint32_t*)dest)[i] = ((uint32_t*)src)[i] & ((uint32_t*)mask)[i]; // this raises SIGBUS on SPARC and other archs that require aligned access.
}
for(i=wordlen<<2; i<len; i++){
dest[i] = src[i] & mask[i];
}
}
但是它需要建立在幾個架構,所以我:
void mask_bytes(unsigned char* dest, unsigned char* src, unsigned char* mask, unsigned int len)
{
unsigned int i;
for(i=0; i<len; i++)
{
dest[i] = src[i] & mask[i];
}
}
我可以寫的東西,比如去更快不結盟接入設備(如86)上想要做這樣的事情:
void mask_bytes(unsigned char* dest, unsigned char* src, unsigned char* mask, unsigned int len)
{
unsigned int i;
unsigned int wordlen = len >> 2;
#if defined(__ALIGNED2__) || defined(__ALIGNED4__) || defined(__ALIGNED8__)
// go slow
for(i=0; i<len; i++)
{
dest[i] = src[i] & mask[i];
}
#else
// go fast
for(i=0; i<wordlen; i++)
{
// the following line will raise SIGBUS on SPARC and other archs that require aligned access.
((uint32_t*)dest)[i] = ((uint32_t*)src)[i] & ((uint32_t*)mask)[i];
}
for(i=wordlen<<2; i<len; i++){
dest[i] = src[i] & mask[i];
}
#endif
}
但我找不到任何關於編譯器定義的宏的好信息(如我的假設上面的)指定了對齊或使用預處理器來確定目標架構對齊的任何聰明方式。我只能測試defined (__SVR4) && defined (__sun)
,但我更喜歡的東西只是工作 TM其他架構需要對齊內存訪問。
CPU使額外的週期得到未對齊的數據並將其移入正確的位置。通常情況下,這會明顯慢於對齊獲取。您應該總是嘗試讀取對齊的... – DipSwitch
就像我一直在使用無法進行交叉對齊副本的系統一樣工作,以至於我剛剛假設存在正常和「快速」副本。 –
不幸的是,這是在一個庫中,我無法控制這個庫的用戶如何對齊他們發送給我的緩衝區。 – nolandda