一种简单强大很囧的优化方法

不多说,直接看代码:

#include <iostream>
#include <ctime>
using namespace std;

void foo(int data)
{
    data *= data;
}

void test_funny_optimize()
{
    //case 0  => result time : 1206 ms
    {
        clock_t startTime = clock();
        for (long long i = 0; i < 1000000000LL; i ++)
        {
            foo(i);
        }
        clock_t stopTime = clock();
        cout << endl;
        cout << "offset is 1" << endl;
        cout << "cost time : " << (stopTime - startTime) << " ms" << endl;        
    }

    //case 1  => result time : 545 ms
    {
        clock_t startTime = clock();
        for (long long i = 0; i < 1000000000LL; i += 2)
        {
            foo(i);
            foo(i + 1);
        }
        clock_t stopTime = clock();
        cout << endl;
        cout << "offset is 2" << endl;
        cout << "cost time : " << (stopTime - startTime) << " ms" << endl;
    }

    //case 2  => result time : 347 ms
    {
        clock_t startTime = clock();
        for (long long i = 0; i < 1000000000LL; i += 3)
        {
            foo(i);
            foo(i + 1);
            foo(i + 2);
        }
        clock_t stopTime = clock();
        cout << endl;
        cout << "offset is 3" << endl;
        cout << "cost time : " << (stopTime - startTime) << " ms" << endl;
    }

    //case 3  => result time : 102 ms
    {
        clock_t startTime = clock();
        for (long long i = 0; i < 1000000000LL; i += 10)
        {
            foo(i);
            foo(i + 1);
            foo(i + 2);
            foo(i + 3);
            foo(i + 4);
            foo(i + 5);
            foo(i + 6);
            foo(i + 7);
            foo(i + 8);
            foo(i + 9);
        }
        clock_t stopTime = clock();
        cout << endl;
        cout << "offset is 10" << endl;
        cout << "cost time : " << (stopTime - startTime) << " ms" << endl;
    }
}
int main(int argc, char* argv[])
{
    test_funny_optimize();
    return 0;
}

vs2013 release模式编译,代码之后是执行结果:

 

当然,这个方法是在循环次数很大时作用才大。

posted @ 2014-05-14 16:00  *神气*  阅读(240)  评论(2编辑  收藏  举报