Jos*_* D. 5 c++ performance destructor
这是我正在处理的代码:
#include <iostream>
#include <map>
using namespace std;
static unsigned long collatzLength(unsigned long n) {
static std::map<unsigned long,int> collatzMap;
int mapResult = collatzMap[n];
if (mapResult != 0) return mapResult;
if (n == 1) {
return 1;
} else {
collatzMap[n] = 1 + collatzLength(n%2==0?n/2:3*n+1);
return collatzMap[n];
}
}
int main() {
int maxIndex = 1;
unsigned int max = 1;
for (int i=1; i<1000000; i++) {
//cout<<i<<endl;
unsigned long count = collatzLength(i);
if (count > max) {
maxIndex = i;
max = count;
}
}
cout<<maxIndex<<endl;
getchar();
cout<<"Returning..."<<endl;
return maxIndex;
}
Run Code Online (Sandbox Code Playgroud)
当我编译并运行这个程序时(使用 Visual Studio 2012 和 Release 构建设置),在程序打印“Returning...”后需要 10 秒(在我的电脑上)关闭
这是为什么?
注意:我知道这个程序写得不好,我可能不应该在 collatzLength 上使用“静态”,也不应该为该函数使用缓存,但我对如何改进此代码不感兴趣,我只是有趣的是为什么关闭需要这么多时间。
| 归档时间: |
|
| 查看次数: |
1074 次 |
| 最近记录: |