Archived

This topic is now archived and is closed to further replies.

Why is Int faster than char??

This topic is 5042 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

#include <time.h> #include <iostream> using namespace std; #define TRIALS 500000 void func1(); void func2(); void main() { time_t time1 = time(NULL); func1(); cout << "Func1 took ->" << (time(NULL) - time1) << " seconds\n"; time1 = time(NULL); func2(); cout << "Func2 took ->" << (time(NULL) - time1) << " seconds\n"; int i=0; } void func1() { for( unsigned int i=0; i < 255; i++) for( unsigned int a=0; a < 255; a++) for( unsigned int b=0; b < 255; b++) for( unsigned int k=0; k < 255; k++){} } void func2() { for( unsigned char i=0; i < 255; i++) for( unsigned char a=0; a < 255; a++) for( unsigned char b=0; b < 255; b++) for( unsigned char k=0; k < 255; k++){} } When I ran the following program i found that incrementing the unsigned int 255^4 times only took 12 seconds while the unsigned char took a wild 35 seconds. Does anyone know why this would be because a char is only 1 byte while a int is 4 so shouldnt the char go faster??

Share this post


Link to post
Share on other sites
Yeah, memory alignment is exactly it. A 32 bit processor works best on 32 bit aligned data. it processes 8-bit data just as fast as 32-bit data, if it is 32-bit aligned. If it isn''t, then it will be slower... unless you use some sort of CPU vector feature (eg MMX) it will never be faster to work directly with chars. The do however have considerable advantages if you use vector features when acting on large arrays, as the array is 1/4 the size as the int version, and can be processed 4x faster.

Share this post


Link to post
Share on other sites