一般來說Float轉成Int,編譯器都會幫我們執行轉換
但是由於平台特性的問題,往往都是會做最保守的轉換
對於遊戲開發注重效能的程式碼來說,常常轉換是很費時的
尤其是當你是開發硬體規格受限的平台時,更是錙銖必較
以下分享一個快速的方式給大家參考
首先定義一個魔術數值(Magic Value)
#define FIST_MAGIC ((((65536.0 * 65536.0 * 16)+(65536.0 * 0.5))* 65536.0))
再寫一個Function
int32 QuickFist(float inval) { double dtemp = FIST_MAGIC + inval; return ((*(int32 *)&dtemp) - 0x80000000); }
Summary
So, heres a small set of rules to summarise how to make your engine faster:
Precalculate as much as possible
Don't calculate anything you don't need
Don't calculate anything twice
Try to use results of previous calculations again, if possible
Look out for occaisions where you can 'spend a penny to save a pound'
Before you code that function in assembly, ask yourself "Have I really got the best solution?"
Experiment!
Take risks
Don't write anything off because it "looks slow"
Explore your target architecture, know its quirks