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

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

  • 相关阅读:
    负载均衡之加权轮询算法(转)
    go 指南学习笔记
    select限制之文件描述符限制
    select的限制
    select实现超时(套接字IO超时设置)
    如何在CentOS 8上安装Puppet
    如何在Ubuntu 20.04 / 18.04或更老版本中安装ifconfig
    关于Ubuntu的Apt安装与使用介绍
    如何在CentOS 8上安装Suricata?
    如何在Ubuntu 20.04上安装PHP Composer
  • 原文地址:https://www.cnblogs.com/xylc/p/3727961.html
Copyright © 2011-2022 走看看