C++11 chrono计时

下面的代码开了好几个线程,等所有线程都运行完毕,统计用了多少时间

其中,每个thread对象都应该调用join,以保证每一个线程在多线程环境下都可以完整的运行,而不被CPU调度而回不来错过了剩下没执行部分的执行。

#include        // std::cout
#include          // std::thread
#include 

bool is_prime(int x)
{
	for (int i = 2; i < x; ++i)
	{
		if (x%i == 0)
		{
			return false;
		}
	}
	std::cout << x << " is prime." << "\n";
	return true;
}

int main()
{
	using namespace std::chrono;
	system_clock::time_point today = system_clock::now();

	std::thread first(is_prime, 444444443);     // spawn new thread that calls foo()
	std::thread second(is_prime, 444444443);  // spawn new thread that calls bar(0)
	std::thread second2(is_prime, 444444443);  // spawn new thread that calls bar(0)
	std::thread second3(is_prime, 444444443);  // spawn new thread that calls bar(0)
	std::thread second4(is_prime, 444444443);  // spawn new thread that calls bar(0)
	std::thread second5(is_prime, 444444443);  // spawn new thread that calls bar(0)

	std::cout << "main, foo and bar now execute concurrently...\n";

	// synchronize threads:
	first.join();                // pauses until first finishes
	second.join();               // pauses until second finishes
	second2.join();               // pauses until second finishes
	second3.join();               // pauses until second finishes
	second4.join();               // pauses until second finishes
	second5.join();               // pauses until second finishes

	system_clock::time_point today2 = system_clock::now();
	auto dur = today2 - today;

	typedef std::chrono::duration seconds_type;
	typedef std::chrono::duration milliseconds_type;
	typedef std::chrono::duration microseconds_type;
	
	auto durSecond = std::chrono::duration_cast(dur);
	auto durMill = std::chrono::duration_cast(dur);
	auto durMicr = std::chrono::duration_cast(dur);

	std::cout << "foo and bar completed. eslaped(second) :" << durSecond.count() << "\n";
	std::cout << "foo and bar completed. eslaped(millisecond) :" << durMill.count() << "\n";
	std::cout << "foo and bar completed. eslaped(microsecond) :" << durMicr.count() << "\n";
	std::cout << "foo and bar completed. eslaped(ticks) :" << dur.count()<<"\n";

	return 0;
}

输出如下:

C++11 chrono计时_第1张图片

从控制台输出可以看到,多线程执行完输出到控制台的时候由于没有加锁,所以都在同时输出,打乱了输出。这正是我们想看到的。

你可能感兴趣的:(C++,11)