C ++多线程代码与单线程执行的时间相同

时间:2016-10-02 17:38:08

标签: c++ multithreading

我有以下代码(多线程版本):

std::vector<std::thread> threads;
for ( size_t i = 0; i < videos.size(); ++i ) {
      threads.push_back(std::thread([&features, i]() {
           for (size_t j = 0; j < videos.at(i).size(); ++j) {
               features.extract(...);
           }
      });
      threads.back().join();
}

问题是单线程版本需要大约3分钟才能执行,多线程需要大约3分钟才能执行。外部for循环两次,因此有两个线程。我不应该看到执行时间有所改善吗?甚至几秒钟?

1 个答案:

答案 0 :(得分:4)

你不应该立即加入......那时你的连续工作与线程创建的开销......

您的代码应如下所示:

std::vector<std::thread> threads;
for (std::size_t i = 0; i != videos.size(); ++i ) {
    threads.emplace_back([&features, i]() {
        for (size_t j = 0; j < videos.at(i).size(); ++j) {
            features.extract(...);
        }
    });
}
for (auto& t : threads) {
    t.join();
}
相关问题