基准测试

Posted evanspudding

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基准测试相关的知识,希望对你有一定的参考价值。

#include <iostream>
#include <memory>
#include <chrono> 

class Timer
{
public:
	Timer()
	{
		m_StartTimepoint = std::chrono::high_resolution_clock::now();
	}

	~Timer()
	{
		Stop();
	}
	void Stop()
	{
		auto endTimepoint = std::chrono::high_resolution_clock::now();

		auto start = std::chrono::time_point_cast<std::chrono::microseconds>(m_StartTimepoint).time_since_epoch().count();
		auto end = std::chrono::time_point_cast<std::chrono::microseconds>(endTimepoint).time_since_epoch().count();

		auto duration = end - start;
		double ms = duration * 0.001;

		std::cout << duration << "us (" << ms << "ms)
";
		
	}
private:
	std::chrono::time_point< std::chrono::high_resolution_clock> m_StartTimepoint;
};


int main()
{

	int value = 0;
	{
		Timer timer;

		for (int i = 0; i < 10000; i++)
			value += 2;
	}
	 
	std::cout << value << std::endl;

	__debugbreak(); //windows api 断点
}

技术图片

//智能指针查看
int main()
{
	struct Vector2
	{
		float x, y;
	};

	std::cout << "make share
";
	{
		std::array<std::shared_ptr<Vector2>, 1000> sharedPtrs;
		Timer timer;
		for (int i = 0; i < sharedPtrs.size(); i++)
			sharedPtrs[i] = std::make_shared<Vector2>();
	}

	std::cout << "new share
";
	{
		std::array<std::shared_ptr<Vector2>, 1000> sharedPtrs;
		Timer timer;
		for (int i = 0; i < sharedPtrs.size(); i++)
			sharedPtrs[i] = std::shared_ptr<Vector2>(new Vector2());
	}

	std::cout << "make unique
";
	{
		std::array<std::unique_ptr<Vector2>, 1000> sharedPtrs;
		Timer timer;
		for (int i = 0; i < sharedPtrs.size(); i++)
			sharedPtrs[i] = std::make_unique<Vector2>();
	}
}

debug模式下会做非常多安全性的工作,所以我们改成release模式下去运行,查看效率,结果如图
技术图片

多次运行结果一致。


以上是关于基准测试的主要内容,如果未能解决你的问题,请参考以下文章

golang基准测试详解

在 C# 中对小代码示例进行基准测试,这个实现可以改进吗?

如何对你的Python代码进行基准测试

Go中的单元测试和基准测试

使用benchmark.js进行前端代码基准测试

单元测试和基准测试