Using Bit Fields to save memory

风流意气都作罢 提交于 2021-02-05 08:48:06

问题


I am currently starting a project on the ps3 at university and we get marks for how optimized the code is.

Me and my partner have been looking at bit fields as we are dealing with millions of numbers between 0 and 255. We figured if we can pack 4 integers into 4 bytes(typical integer sized block of memory) instead of just one then we can quarter the memory used. We see dealing with the data to be one of the largest optimisations we could make and we are looking into everything. Is it worth the hassle? It seems something that is rather difficult to get on with as far as editing the ints goes. We also have the problem that ideally we need different bit fields dependant on the numbers, as up to 255 requires 9 bits but most will not require this many bits.

We can also then pass the data to the spu processors quickly and hopefully see massive improvements when we introduce parallelism into the code.


回答1:


As stated in the comments:

"Optimization is often a trade-off between speed and space. Bitfields can save space but be slower to process than integers."

Bitfields are rarely used for couple of reasons

  • they are complex to manipulate and don't tend to produce huge savings on memory usage. If your values are small enough to warrant a bitfield, then a char should do the job adequately, 8 bits in a char vs say, an int_32 with 32, without adding overhead for accessing the data.
  • they are implementation specific - watch out.

General rule of thumb:

  • Make it work
    • If slow, make it work faster
    • If too big, make it more compact

(note that you can estimate the size beforehand if you have an idea of what you will be storing. Until you get down to optimising cache lines (bit of both speed and memory) as long as it will 'fit', you can probably give yourself a tick on memory usage)

FYI, the most common usage of bitfields is to pack data into datastructures designed for transmission. This is just the first example I could find




回答2:


You just need int8_t (signed) or uint8_t (unsigned) 8 bit integers from <cstdint> C++ header (or <stdint.h> in C99). No need to use bit fields (which are unportable, slow, and uneasy to use - e.g. you can't take their address or reference).

For parallel vector processing, consider also perhaps OpenCL and OpenMP and eventually OpenACC. Better use a very recent compiler, which also supports C++11. Beware that SPU are very hardware specific.

Depending on your application, you might be a bit disappointed by SPUs real life performance, and neither OpenCL nor OpenMP or OpenACC are silver bullets. Parrallelism is hard.



来源:https://stackoverflow.com/questions/26657832/using-bit-fields-to-save-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!