tags:

views:

309

answers:

4

My application runs on a pSOS operating system. The code is compiled with Diab C compiler.

The application defines a number of counters which have been declared as

unsigned int call_count;

As there are chances of some of these overflowing in a small time frame, I have decided to declare the counters as

unsigned long long int call_count;

This I believe would not overflow at least during my lifetime.

My question is this conversion harmless? Are there any overhead that I need to concerned with. When the application is under stress the call_count would be incremented incessantly. Can performance take a hit ? A SNMP manager would be querying these counters every 15 seconds as well.

+1  A: 

I doubt there is a performance issue, at least if you use a 64 bit processor, since the variable is almost always in the cache.

Mehrdad Afshari
+1  A: 

Within broad limits, the change is harmless. You will need to be sure that any code accessing the value is prepared to handle a 64-bit quantity, and any code that formats its value will need to be changed, but otherwise, it should be safe enough -- in the absence of any information about other code that would be broken by the change.

Jonathan Leffler
A: 

You should be fine.

I assume (from the pSOS) that you're coding to a Moto 68000, which is a 32-bit processor; working with 64-bit numbers is slightly slower there because it needs a few more instructions (eg, add, check carry, branch or add to high word) but I doubt you're worried much about a four cycle cost. If you are on a 64-bit processor, then 64-bit ops are exactly as fast as 32-bit ones.

Doing this will increase your memory storage overhead of course, but again that's only a concern if you've a great many structures containing these counters.

Crashworks
+2  A: 

Is your code assuming that incrementing a 32-bit variable is an atomic operation? Incrementing a 64-bit variable on a 32-bit CPU probably won't be atomic unless you go out of your way to make it so.

Example:

  1. call_count equals 0x00000005FFFFFFFF when a call comes in.
  2. The lower half of call_count is incremented: call_count gets set to 0x000000500000000 and the CPU's carry bit gets set to 1.
  3. The upper half of call_count is incremented by the carry bit: call_count gets set to 0x0000000600000000.

If another thread or an interrupt handler reads the value of call_count between steps 2 and 3, it will get the wrong result (0x000000500000000 instead of 0x000000600000000). The solution is to synchronize access to call_count. A few possibilities:

  • Disable interrupts (if appropriate)
  • Serialize access using a lock
  • Read and write using atomic/interlocked functions (example: InterlockedIncrement() on Windows)
bk1e