経過時間を測定するために並列タスクを実行する必要はありません。C++11 での例:
#include <chrono>
#include <string>
#include <iostream>
int main()
{
auto t1 = std::chrono::system_clock::now();
std::string s;
std::cin >> s;
// Or whatever you want to do...
auto t2 = std::chrono::system_clock::now();
auto elapsedMS =
(std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1)).count()
std::cout << elapsedMS;
}
編集:
複数のタスクを並行して起動する方法に関心があるようですので、ここにヒントを示します (ここでも C++11 を使用します)。
#include <ctime>
#include <future>
#include <thread>
#include <iostream>
int long_computation(int x, int y)
{
std::this_thread::sleep_for(std::chrono::seconds(5));
return (x + y);
}
int main()
{
auto f = std::async(std::launch::async, long_computation, 42, 1729);
// Do things in the meanwhile...
std::string s;
std::cin >> s;
// And we could continue...
std::cout << f.get(); // Here we join with the asynchronous operation
}
上記の例では、少なくとも 5 秒かかる長い計算が開始され、その間に他の処理が行われます。その後、最終的にget()
、future オブジェクトを呼び出して非同期計算に参加し、その結果を取得します (まだ終了していない場合は、終了するまで待機します)。