Click here to Skip to main content
15,881,173 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How do you force memory alginment on a large data chunk? Or does it happen for you.

Specifically on valarray am I guranteed optimal performance from the 0th index?

Also is there a way to check what the best alignment is?

For example, assumming the memory of the system is aligned in 32 bit chunks (meaning when the CPU requests a memory address it gets the whole 32 bit chunk not just a byte even if a byte was requested)
and I have a valarray[unsinged char] alignedArray defined then the access to alignedArray[0] thru alignedArray[3] should not make more than one call into memory (should reside in the registers still).

To resummarize I have 2 questions. How do you check the memory alignment (programatically) and how do you ensure your 0 index (or atleast a known index) is at the start of the word?
Posted
Updated 8-Sep-10 10:49am
v2

1 solution

// how do you ensure your 0 index (or atleast a known index) is at the start of the word?
bool TestWordBoundary(void* pTest)
{
  INT_PTR pointer = (INT_PTR) pTest;
  return (0 == pointer % sizeof(WORD));
}

void Yours()
{
  const char* szBufferTest("content");
  ASSERT(TestWordBoundary(&szBufferTest[0]));
  ASSERT(!TestWordBoundary(&szBufferTest[1]));
}
 
Share this answer
 
Comments
[no name] 9-Sep-10 8:52am    
So the address of the pointer should be in intervals of the WORD size?
But my follow ups are how are you defining INT_PTR and more importantly how are you defining WORD? Each system (depending on HW) may vary the definition of its HW word. How are you ensuring it is correct.
Also what you are showing just tests the boundry. It does not correct it. I do not believe it is safe to arbitrarily shift the pointer location to non allocatted memory.
Eugen Podsypalnikov 9-Sep-10 9:11am    
1. I have not used any term of a "pointer address", but one of a "pointer" :)
2. You can not "correct" an data address, but you can copy the addressed data :) :
{
char* szTestBuffer = "content";
WORD* pwData = (WORD*) &szTestBuffer[1]; // an odd address !
#ifdef _X86_
(*pwData)++; // it is OK on x86
#elif defined(MIPS)
// (*pwData)++; // it is not OK on MIPS
WORD wTemp(0); // an even address
memcpy(&dwTemp, pwData, sizeof(WORD));
wTemp++;
memcpy(pwData, &dwTemp, sizeof(WORD));
#endif
ASSERT('p' == szTestBuffer[1]); // :)
}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900