The basic & regular conversion method (int) is a good one, but also it may cause data lost (always truncates the float or double data.)
For example :
1 2 3 4
|
float f = 7.23;
int i = int(f); //= 7 (Correct !!!)
float f2 = 7.86;
int i2 = int(f2);//= 7 - !?!?!?!?
|
And solutions : The round(), floor() are very powerful functions, but it can only help you when you really want it to be rounded down or up....
I learnt the assembly language and I've found out the solution. It only uses two assembly code commands so we called it 'ultra-super-fast float to int conversion'. It automatically rounds the value up or down and most likely it should faster and more convenient than round(), floor()... ???
Now, the code is :
1 2 3 4 5
|
inline int floattoint(float f){int nResult;
_asm fld f;
_asm fistp nResult;
return nResult:}
// And double? - Simply change the float parameter slot -> double
|
And another similar test :
1 2 3 4 5
|
//Copy the code and test
float f = 9.26;
int i = floattoint(f); //= 9 (Correct !)
float f2 = 9.89;
int i2 = floattoint(f2); //= 10 (Very good !!!)
|
Also I found out a simple but powerful method to test & compare the code performance. It records the time elapsed after loop(s). And here, the testing algorithm :
1 2 3 4 5 6 7 8 9 10
|
//#include <time.h>
//int nInt;
int nStart = clock();
//Try doing a billion loop
for (long i = 0; i < 1000000000; i ++ )
{//Put your test code here
nInt = floattoint(10.94);
}
int nEnd = clock();
printf("Time elapsed : %.3f - Result : %d \n", (nEnd - nStart) / 1000.0f, nInt);
|
You can record the peforming time of these above conversions. Or any your own code (If you doubt)...
And finally, a small note : Make sure the 'inline' word is always kept otherwise it will negative the result and kill the performance gain... :P
What do you think?