我在* nix。在looptest.cpp
#include <iostream>
#include <time.h>
int main()
{
double sum = 0.0;
int n ;
std::cout << "n ?" << std::endl;
std::cin >> n ;
clock_t t_start = clock();
for (int i = 0 ; i < n ; ++i)
{
sum+= static_cast<double>(i);
}
clock_t t_end = clock();
clock_t diff = t_end - t_start;
double diffd = static_cast<double>(diff)/CLOCKS_PER_SEC;
std::cout << diffd << " seconds." << std::endl;
sum*=1.0;
return 0;
}
使用intel c ++编译器(icpc(ICC)14.0.4 20140805,2013)编译如下:
/opt/intel/bin/icpc looptest.cpp -o looptest
当我测试它时,我有以下奇怪的结果:
My-MacBook-Air:tmp11 XXXX$ ./looptest
n ?
10000
4e-06 seconds.
My-MacBook-Air:tmp11 XXXX$ ./looptest
n ?
100000
3e-06 seconds.
My-MacBook-Air:tmp11 XXXX$ ./looptest
n ?
1000000
3e-06 seconds.
My-MacBook-Air:tmp11 XXXX$ ./looptest
n ?
1000000000
2e-06 seconds.
My-MacBook-Air:tmp11 XXXX$ ./looptest
n ?
4294967295
3e-06 seconds.
奇怪,不是吗?这里发生了什么 ?当然,使用gnu-5.2 g++
而不是icpc
进行编译会得到预期的结果(当n增加时,时间会增加。)
答案 0 :(得分:4)
sum
,因此删除了对变量的所有分配。这使得for循环变空,所以它也被删除了。因此剩下的就是:
#include <iostream>
#include <time.h>
int main()
{
int n ;
std::cout << "n ?" << std::endl;
std::cin >> n ;
clock_t t_start = clock();
clock_t t_end = clock();
clock_t diff = t_end - t_start;
double diffd = static_cast<double>(diff)/CLOCKS_PER_SEC;
std::cout << diffd << " seconds." << std::endl;
return 0;
}
有效地衡量一次拨打clock()
的速度。
查看编译后的代码,找出编译器所做的优化。 GCC&#34;应该&#34;能够执行相同的优化,但只有在将参数-O
(-O2
,-O3
,-Os
)添加到调用时才会执行此操作。