7.40. How do I round floating point numbers efficiently?
There are two primary methods for rounding numbers:
Convert.ToInt32
Cast or Fix (C# or VB)
Convert.ToInt32 automatically handles rounding, where remainders of .5 and greater cause the number to be rounded up. Casting or using Fix requires adding .5 to the number to ensure that it will round properly, as these methods simply remove the remainder.
Profiling on the emulator and a Compaq iPAQ H3600 series device yielded the following results for 1 million operations of each method, where num is a float set to 3.6F:
Emulator
iPAQ
Operation
Debug (ms)
Release (ms)
Debug (ms)
Release (ms)
C#: Convert.ToInt32(num)
1321
1109
6264
6283
C#: (int)(num + .5F)
170
49
1479
59
VB: Convert.ToInt32(num)
1218
1232
6531
6517
VB: Fix(num + .5F)
3873
3677
18144
17955
Thus, by examining the release build results for the device, it can be concluded that on the current generation of devices it is most efficient to use casting in C# and Convert.ToInt32 in
本文作者:佚名 来源:www.weste.net
CIO之家 www.ciozj.com 微信公众号:imciow