zoukankan      html  css  js  c++  java
  • 一种简单强大很囧的优化方法

    不多说,直接看代码:

    #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模式编译,代码之后是执行结果:

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

  • 相关阅读:
    jdbc操作数据库并自动获取字段类型
    oracle sqlplus登陆命令
    2014木瓜移动校园招聘笔试题
    线段树总结
    JAVA的Split小技巧
    百度地图2.2框架黑屏和只有网格处理方法
    Zend Studio 实用快捷键大全
    Ext4中获取下拉框的值
    Java如何显示不同语言的时间?
    Java如何以不同国家的格式显示时间?
  • 原文地址:https://www.cnblogs.com/xylc/p/3727961.html
Copyright © 2011-2022 走看看