Quick conversion of double to int(2014-01-19 13:39:56) reprinted
Tags: double long numeric type conversion fast |
|
The graphical representation uses a double, which displays the small recipe for increasing efficiency with int. But, you know. The most common type conversion is actually quite slow: int a = (int) dbl; Today, when searching for fixed-point arithmetic, I inadvertently see an article that is a quick way to double int.
First paste the code, in fact, the source code of LUA,:-)
=============================================================
#if defined (lua_number_double) &&!defined (lua_ansi) &&!defined (__sse2__) && \ (defined (__i3 86) | | Defined (_m_ix86) | | Defined (__I386__)) union luai_cast {double l_d; Long l_l; }; #define LUA_NUMBER2INT (i,d) \ {volatile union luai_cast u; u.l_d = (d) + 6755399441055744.0; (i) = u.l_l; } #define Lua_number2integer (i,n) lua_number2int (i, N) #else #define LUA_NUMBER2INT (i,d) ((i) = (int) (d)) #define Lua_nu Mber2integer (I,d) ((i) = (Lua_integer) (d)) #endif
===========================================================
The original post is here http://rangercyh.blog.51cto.com/1444712/1313162
The authors also analyzed the reasons.
I will not wordy, remember this method is good.
Finally, I did a little experiment to compare the speed difference between this method and the direct type conversion.
#define LOOPS 200000000
Union luai_cast {Double l_d; long l_l;};
#if 1
#define Dbl2int (d, i) \
{Volatile union luai_cast u; u.l_d = (d) + 6755399441055744.0; (i) = u.l_l; }
#else
#define Dbl2int (d, i) (d) +=6755399441055744.0; (i) =* (int*) &d;
#endif
int main (int argc, char* argv[])
{
printf ("Hello world!\n");
Long Val;
Double dbl=7.56;
Long T1 = GetTickCount ();
for (int i=0; i
{
Dbl2int (Dbl, Val);
Dbl=i;
Val+=1;
}
Long t2 = GetTickCount ();
printf ("Start:%d\n end:%d\ntime=%d\n", T1, T2, T2-T1);
dbl=7.86;
long t3 = GetTickCount ();
for (int j=0; j
{
val= (int) dbl;
Dbl=j;
Val+=1;
}
long T4 = GetTickCount ();
printf ("Start:%d\n end:%d\ntime=%d\n\n%f\n\n", T3, T4, T4-t3, 1.0* (T4-T3)/(T2-T1));
printf ("val=%d\n", Val);
return 0;
}
The results of the operation are as follows:
Hello world!
start:11795010
end:11795761
time=751
start:11795761
end:11799546
time=3785
5.039947
val=199999999
Press any key to continue
5 times times the speed difference.
At the same time, it also compares the speed difference between the operation of the joint and the pointer, and it takes time to take the value with the pointer.