ash*_*eef 6 algorithm math optimization performance vba
遇到一些代码,其中通过将数字转换为字符串然后使用len()来确定位数.
Function numOfDigits_len(n As Long) As Long
numOfDigits_len = Len(Str(n)) - 1
End Function
Run Code Online (Sandbox Code Playgroud)
现在虽然这有效但我知道与任何不使用字符串的方法相比它会很慢,所以我写了一个使用log()的方法.
Function numOfDigits_log(n As Long) As Long
numOfDigits_log = Int(Log(n) / Log(10)) + 1
End Function
Run Code Online (Sandbox Code Playgroud)
将运行时间减少1/2,这很好,但在特定情况下发生了一些奇怪的事情.
n numOfDigits_log(n)
===== ====================
999 3
1000 3
1001 4
Run Code Online (Sandbox Code Playgroud)
它无法1000正常处理.我认为这是因为浮点和舍入问题.
Function numOfDigits_loop(ByVal n As Long) As Long
Do Until n = 0
n = n \ 10
numOfDigits_loop = numOfDigits_loop + 1
Loop
End Function
Run Code Online (Sandbox Code Playgroud)
写了这个,当数字大于10 ^ 6时,结果变慢了约10%,并且随着n变大,似乎变得越来越慢.如果我是务实的话哪个好,但我想找到更理想的东西.
现在我的问题是,有没有办法准确使用log()方法.我可以做点什么
Function numOfDigits_log(n As Long) As Long
numOfDigits_log = Int(Log(n) / Log(10) + 0.000000001) + 1
End Function
Run Code Online (Sandbox Code Playgroud)
但它似乎非常"hacky".有没有比log()方法更快或更快的更好的方法?注意:我意识到在很多情况下这种优化是没有意义的,但现在我遇到过这种情况我想"修复"它
我以前回答过这个问题,但我找不到它,所以这里是基础知识:
int i = ... some number >= 0 ...
int n = 1;
if (i >= 100000000){i /= 100000000; n += 8;}
if (i >= 10000){i /= 10000; n += 4;}
if (i >= 100){i /= 100; n += 2;}
if (i >= 10){i /= 10; n += 1;}
Run Code Online (Sandbox Code Playgroud)
那是在 C 语言中,但你明白了。
| 归档时间: |
|
| 查看次数: |
101 次 |
| 最近记录: |