#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);
}