C++多线程进行加速算法

一、直接使用版本

#include <iostream>
#include <vector>
#include <math.h>
#include <thread>
#include <chrono>

// 计算函数,将平方计算分散到多个线程中
void calculate_square_multithread(std::vector<int>& nums, int num_threads) {
    int task_count = nums.size() / num_threads;
    std::vector<std::thread> threads(num_threads);

    for (int i = 0; i < num_threads; ++i) {
        int start = i * task_count;
        int end = (i + 1) * task_count;
        threads[i] = std::thread([&nums, start, end]() {
            for (int j = start; j < end; ++j) {
                nums[j] *= nums[j];
            }
        });
    }

    for (auto& t : threads) {
        t.join();
    }
}

// 计算函数,使用单线程计算数组的平方
void calculate_square_singlethread(std::vector<int>& nums) {
    for (int i = 0; i < nums.size(); ++i) {
        -1.0f * logf((i * i * 1.0f / 10) - 1.0f);
        -1.0f * logf((i * i * 1.0f / 10) - 1.0f);
        -1.0f * logf((i * i * 1.0f / 10) - 1.0f);
        -1.0f * logf((i * i * 1.0f / 10) - 1.0f);
        nums[i] *= nums[i];
    }
}

int main() {
    const int array_size = 990000000; // 数组大小
    std::vector<int> nums(array_size);

    // 填充数组
    for (int i = 0; i < array_size; ++i) {
        nums[i] = i;
    }

    // 使用单线程计算数组平方并计时
    auto start = std::chrono::high_resolution_clock::now();
    calculate_square_singlethread(nums);
    auto end = std::chrono::high_resolution_clock::now();
    auto duration_single = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
    std::cout << "Single thread time: " << duration_single.count() << " milliseconds" << std::endl;

    // 使用多线程计算数组平方并计时,假设使用4个线程
    start = std::chrono::high_resolution_clock::now();
    calculate_square_multithread(nums, 4);
    end = std::chrono::high_resolution_clock::now();
    auto duration_multithread = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
    std::cout << "Multi-thread time: " << duration_multithread.count() << " milliseconds" << std::endl;
    std::cout << "Speedup: " << duration_single.count() / duration_multithread.count() << "x" << std::endl;

    return 0;
}

结果

Single thread time: 69591 milliseconds
Multi-thread time: 2193 milliseconds
Speedup: 31x

二、带返回值使用

#include <iostream>
#include <thread>
#include <vector>
#include <future>
 
int calculate(int value) {
    // 模拟耗时计算
    std::this_thread::sleep_for(std::chrono::seconds(2));
    
    return value * value;
}
 
void joinFutures() {
    int numThreads = 5;
    std::vector<std::future<int>> futures;
  
    for (int i = 0; i < numThreads; ++i) {
        int value = i + 1;
        
        // 创建新线程并返回其未完成状态的 future 对象
        auto future = std::async([value](){
            return calculate(value);
        });
      
        // 存储每个线程的 future 对象到 vector 中
        futures.push_back(std::move(future));
    }
  
    // 遍历所有的 future 对象,通过 get() 函数获取结果
    for (auto& future : futures) {
        try {
            int result = future.get();
            
            // 输出每个线程的结果
            std::cout << "Result from thread #" << result << ": ";
            std::cout << result << std::endl;
        } catch (const std::exception& e) {
            std::cerr << "Exception caught in main thread: " << e.what() << std::endl;
        }
    }
}
 
int main() {
    joinFutures();
  
    return 0;
}
  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

誓天断发

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值