如果您只想测量执行时间,我认为您应该将now和end语句放在
threadFunction
只有在工作完成的地方,如下面的代码所示。
#include <map>
#include <iostream>
#include <memory>
#include <chrono>
#include <vector>
#include <thread>
#include <mutex>
#include <functional>
class ParallelTask
{
public:
ParallelTask();
// Join the treads
~ParallelTask();
public:
inline std::vector<int> GetPath() const { return path; }
void Execute();
private:
std::thread thread;
mutable std::mutex mutex;
std::function<void()> threadFunction;
bool completed;
std::vector<int> path;
};
ParallelTask::ParallelTask()
{
threadFunction = [this]() {
{
auto start = std::chrono::system_clock::now();
std::lock_guard<std::mutex> lock(mutex);
this->completed = true;
auto end = std::chrono::system_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
std::cout << "elapsed time" << elapsed.count() << std::endl;
}
};
}
ParallelTask::~ParallelTask()
{
if (thread.joinable())
thread.join();
}
void ParallelTask::Execute()
{
this->completed = false;
// Launch the thread
this->thread = std::thread(threadFunction);
}
int main()
{
std::map<int, std::unique_ptr<ParallelTask>> parallelTaskDictionary;
for (size_t i = 0; i < 10; i++)
{
parallelTaskDictionary.emplace(i, std::make_unique<ParallelTask>());
parallelTaskDictionary[i]->Execute();
}
parallelTaskDictionary.clear();
return 0;
}
它给出一个输出:
elapsed time1
elapsed time0
elapsed time0
elapsed time0
elapsed time0
elapsed time0elapsed time
0
elapsed time0
elapsed time0
elapsed time0
因为我们排除了纺线所需的时间。
作为一个理智的检查,如果你真的想看到真正工作的效果,你可以加上,
using namespace std::chrono_literals;
std::this_thread::sleep_for(2s);
对你
线程函数
,让它看起来像这样
ParallelTask::ParallelTask()
{
threadFunction = [this]() {
{
auto start = std::chrono::system_clock::now();
std::lock_guard<std::mutex> lock(mutex);
this->completed = true;
using namespace std::chrono_literals;
std::this_thread::sleep_for(2s);
auto end = std::chrono::system_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
std::cout << "elapsed time" << elapsed.count() << std::endl;
}
};
}
结果是,
elapsed time2000061
elapsed timeelapsed time2000103
elapsed timeelapsed time20000222000061
elapsed time2000050
2000072
elapsed time2000061
elapsed time200012