使用async(),但性能时间较差

问题描述 投票:0回答:1

我从 The Cherno Youtube 频道观看了 async() 的用法,并尝试在我的代码中执行此操作。然而,使用 async() 的结果时间比普通方法要慢得多。

嗨,我从 The Cherno Youtube 频道观看了 async() 的用法,并尝试在我的代码中执行此操作。然而,使用 async() 的结果时间比普通方法要慢得多。

我尝试实现一个加法函数将独立值推回到向量中,并且由于值是独立的,因此我使用 async() 函数尝试通过多线程来实现,并使用库实现一个名为 Time 的类来记录性能。然而,随着大小的增加,使用 async() 的结果比正常推回的速度要慢。

#include <iostream>
#include <future>
#include <chrono>
#include <vector>
#include <mutex>


//A class Time to record the function running time
class Time{
...
};



//Implement async()
static std::mutex the_lock;

static void addition(std::vector<int>* array, int index){
    int num = index + 2;
    std::lock_guard<std::mutex> lock (the_lock);
    array->push_back(num);
}


//Main function
#define timer() Time timer##__LINE__
int main()
{
    std::vector<int> array;
    int test_size = 100;
    std::vector<std::future<void>> f;


    
    /* Compare the asynchrouns push back method and normal push back method by recording their running time */
    {
        timer();
        for(int i = 0; i < test_size; ++i){
            f.push_back(std::async(std::launch::async, addition, &array, i));
        }
    }


    {
        timer();
        for(int i = 0; i < test_size; ++i){
            array.push_back(i + 2);
        }
    }
    
    
    return 0;
}

尺寸100的结果

Asychrouns Function is running...
1436 μs

Normal push back function is running...
27 μs

尺寸1000

Asychrouns Function is running...
8351 μs

Normal push back function is running...
25 μs

尺寸 10000 更差。

有人可以帮我检查一下哪里出了问题吗?

c++ multithreading asynchronous concurrency
1个回答
0
投票

异步版本运行速度比同步版本慢的原因主要是由于创建线程和使用互斥锁同步对共享向量资源的访问的开销。多线程,尤其是大量线程,并不总是最快的解决方案,特别是对于轻量级任务或涉及大量同步时。

© www.soinside.com 2019 - 2024. All rights reserved.