W c++ ze strukturami trzeba uważać, np ten kod:
// Example program
#include <iostream>
#include <string>
struct A {
//bitmap file header (14 bytes)
char Sign1,Sign2; //2
unsigned int File_Size; //4
unsigned int Reserved_Dword; //4
unsigned int Data_Offset; //4
//bitmap info header (16 bytes)
unsigned int Dib_Info_Size; //4
unsigned int Image_Width; //4
unsigned int Image_Height; //4
unsigned short Planes; //2
unsigned short Bits; //2
};
int main()
{
std::string name;
std::cout << sizeof(A)<<std::endl;
}
wklejony do http://cpp.sh/ zwraca 32 a nie 30 :)
I jeszcze ciekawe zastosowanie pakowania liczb do optymalizacji kodu:
#include <iostream>
#include <sys/time.h>
unsigned char* test;
unsigned int size = 1024 * 1024 * 200;
long ms() {
struct timeval tp;
gettimeofday(&tp, NULL);
return tp.tv_sec * 1000 + tp.tv_usec / 1000;
}
long bitOptTest(unsigned char* test) {
long start1 = ms();
unsigned int *t = (unsigned int*)test;
for(int i=0;i<size/4; i++) {
t[i] = 0x19191919;
}
unsigned long sum = 0;
for(int j=0; j<100; j++) {
for(unsigned int i=0; i<size/4; i++) {
unsigned int v = t[i];
sum += ((v>>24)&0xFF) + ((v>>16)&0xFF) + ((v>>8)&0xFF) + (v&0xFF);
}
}
long end1 = ms();
std::cout<<sum<<std::endl;
return (end1-start1);
}
long simpleSumTest(unsigned char* test) {
long start2 = ms();
for(unsigned int i=0; i<size; i++) {
test[i] = 25;
}
unsigned long sum = 0;
for(int j=0; j<100; j++) {
for(unsigned int i=0; i<size; i++) {
sum += test[i];
}
}
long end2 = ms();
std::cout<<sum<<std::endl;
return (end2-start2);
}
int main(int argc, char* argv[]) {
test = new unsigned char[size];
long time1 = bitOptTest(test);
long time2 = simpleSumTest(test);
std::cout<<"BIT OPTIMAL 1: "<<time1/1000.0<<std::endl;
std::cout<<"SIMPLE SUM 2: "<<time2/1000.0<<std::endl;
delete[] test;
return 0;
}
Wynik dla O2 i O3 :
$ c++ -O2 main.cpp -o main
$ ./main.exe
524288000000
524288000000
BIT OPTIMAL 1: 5.734
SIMPLE SUM 2: 8.84
$ c++ -O3 main.cpp -o main
$ ./main.exe
524288000000
524288000000
BIT OPTIMAL 1: 2.618
SIMPLE SUM 2: 5.593