• std::async方式循环提速


    #include <future>
    double
    CControl::GetSum(int data) { double sum = 0; for (int j = 0; j < data; j++) { sum += j + 0.1 * pow(j, 4) + 88.8 * pow(j, 3); } return sum; }
    void Test()
    {
      int
    cycCount = 8; int addCount = 120000; CString strmsg; double t1, t2; DWORD dwStart = GetTickCount(); double sum = 0; for (int i = 0; i < cycCount; i++) { for (int j = 0; j < addCount; j++) { sum += j + 0.1 * pow(j,4) + 88.8 * pow(j, 3); } } t1 = GetTickCount() - dwStart; strmsg.Format("%0.3f %0.3f ", t1, sum); Sys_State state = m_SysState; dwStart = GetTickCount(); double result = 0; std::vector<std::future<double>> fut(cycCount); //速度会比单流程方式快2-3倍
        

    const int32_t threadNum = static_cast<int32_t>(std::thread::hardware_concurrency());
    strmsg.Format("%d", threadNum); //threadNum 等于CPU核心数,可以根据这个开这么多个异步线程

        for (int i = 0; i < cycCount; i++)
        {
            //函数方式
            //fut[i] = std::async(std::launch::async,GetSum, addCount);
            //lambda 方式,传参数只能用局部变量,不能用类成员变量
            fut[i] = std::async(std::launch::async, [addCount, state]{
                double sum = 0;
                for (int j = 0; j < addCount; j++)
                {
                    sum += j + 0.1 * pow(j, 4) + 88.8 * pow(j, 3);
                }
                return sum; });
        }
        //auto v = fut[0].get();  
        for (int i = 0; i < cycCount; i++)
        {
            fut[i].wait();
            result += fut[i].get();
        }
        t2 = GetTickCount() - dwStart;
        strmsg.Format("%0.3f %0.3f result:%0.3f %0.3f", t1, t2, sum, result);
        AfxMessageBox(strmsg);
    }
  • 相关阅读:
    题库重整
    计算几何练习题――直线交点
    An Easy Task
    简单排序
    IBM Minus One
    Binary Numbers
    去掉VS2010代码中文注释的红色下划线
    【转】Windows socket基础
    【STL】vector的insert方法详解
    window7下 cocos2dx android交叉编译环境部署小结
  • 原文地址:https://www.cnblogs.com/profession/p/15549388.html
Copyright © 2020-2023  润新知