简体   繁体   中英

How to reach best performence with different data types?

I am working on custom class, which holds Date and Time. The main goal of that class is reaching the best performance. My target platform is Linux Currently, I hold members like this

Year - int
Month - int
Day - int
Hour- int
Min - int
Sec - double (because I need milisecs as well).

What I am thinking now is too change types to following

   Year - unsigned short
    Month - unsigned char
    Day - unsigned char
    Hour- unsigned char
    Min - unsigned char
    Sec - unsigned char
    Milisec - unsigned short

Which gives me 2 + 1 + 1 + 1 + 1 + 1 + 2 = 9 bytes. As you already guessed I want to fit my class into 8 byte(there are no other members). So what is the best approach to solve it, to merge(eg seconds and miliseconds) and use bit masks for retrieving values? Will it affect performance? And what if user passes integers to some setter, would type cast affect performance also ?

Thanks on advance.

There are multiple options you have here. The most compact way would be to have an integer timestamp. It would take a bit of processing to unpack it though. Another option is to use C++ bitfields to pack things tighter. For example, month only needs 4 bits, day 5 bits, minutes and seconds 6 bits. It should make things a bit slower, but only in theory. It all depends on the number of these dates you have and on the amount and kind of processing you're going to perform on them. In some cases having the struct tightly packed into bitfields would increase the performance because of higher memory throughput and better cache utilization. In other cases, the bit manipulation might become more expensive. Like always with performance, better not to guess, but measure .

The simpliest way here is to put pair of sec and millisec into one int (two bytes). You don't need separate Sec (unsigned char) and Milisec (unsigned short), because you can put number from 0 to 60000 into one unsigned short.

Let's call it milliSecPack (unsigned short).

milliSecPack = 60 * Sec + Milisec;

And

Sec = milliSecPack / 1000;
Milisec = milliSecPack % 1000;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM