2013-10-05 40 views
4

我正在考虑以下C++程序:32位和64位:大规模运行时差分

#include <iostream> 
#include <limits> 


int main(int argc, char **argv) { 
    unsigned int sum = 0; 
    for (unsigned int i = 1; i < std::numeric_limits<unsigned int>::max(); ++i) { 
     double f = static_cast<double>(i); 
     unsigned int t = static_cast<unsigned int>(f); 
     sum += (t % 2); 
    } 
    std::cout << sum << std::endl; 
    return 0; 
} 

我使用的gcc /克++编译器,G ++ -v给出gcc版本4.7.2 20130108 [GCC-4_7-分支修订版195012](SUSE Linux)。 我运行的是openSUSE 12.3(x86_64),并且有一个Intel(R)Core(TM)i7-3520M CPU。

运行

g++ -O3 test.C -o test_64_opt 
g++ -O0 test.C -o test_64_no_opt 
g++ -m32 -O3 test.C -o test_32_opt 
g++ -m32 -O0 test.C -o test_32_no_opt 

time ./test_64_opt 
time ./test_64_no_opt 
time ./test_32_opt 
time ./test_32_no_opt 

产生

2147483647 

real 0m4.920s 
user 0m4.904s 
sys  0m0.001s 

2147483647 

real 0m16.918s 
user 0m16.851s 
sys  0m0.019s 

2147483647 

real 0m37.422s 
user 0m37.308s 
sys  0m0.000s 

2147483647 

real 0m57.973s 
user 0m57.790s 
sys  0m0.011s 

使用浮动而不是双,优化的64位变体甚至在完成2.4秒,而其他的运行时间留大致相同。然而,随着float的不同,我会根据优化获得不同的输出,这可能是由于更高的处理器内部精度。

我知道64位可能有更快的数学,但我们有一个因子7(和近15浮点数)在这里。

我将不胜感激这些运行时间差异的解释。

+0

标杆是有意义的。我相信,即使在'-m32'中,'double'也是8个字节。 –

回答

5

问题不在于32位与64位,而是缺少SSE和SSE2。当编译为64位时,gcc认为它可以使用SSE和SSE2,因为所有可用的x86_64处理器都具有它。

使用-msse -msse2编译您的32位版本,运行时差异几乎消失。

我的完整性基准测试结果:要求编译器优化,只有当

-O3 -m32 -msse -msse2  4.678s 
-O3 (64bit)    4.524s 
+0

为获得最佳效果,请使用“-m32 -march = native”。 – kfsone

+0

为了获得最佳效果,请使用“-m32 -march = native”(对于编辑max的评论感到抱歉) – kfsone