dynamic_cast&&基准测试(C++基础)

dynamic_cast

dynamic_cast是专门用于沿继承层次结构进行的强制类型转换,更像是一个函数, 不是编译时进行的类型转换,而是在运行时计算,正因如此,有小性能损失。

在基类和派生类之间相互转换。dynamic_cast常用来做验证,下图中开启运行时检查。

class Entity {
public:
	virtual void PrintName9() {}
};
class Player : public Entity{};
class Enemy : public Entity{};
int main() {
	Player* player = new Player();
	Entity* e = player;
	Enemy* e1 = new Enemy();
	//Enemy* e2 = (Enemy*)e;
	//Enemy* e2 = static_cast<Enemy*>(e);
	Player* e2 = dynamic_cast<Player*>(e1);
	Player* e3 = dynamic_cast<Player*>(e);
	//类似Java可以进行类型验证
	if (dynamic_cast<Player*>(e1) == NULL) {
		std::cout << "error";
	}
}

如果类型转换无效,就说明不是你声称的给定类型,那么就会返回null

使用需要rtti是打开状态,在绝大多数状态,打开会增加开销,但关闭可能会带来错误,如果只想优化,编写非常快的代码,需要避免使用。

基准测试

在这里复习了 如何编写计时类:

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 << "ns:" << duration<< "(ms:" << ms << ")" << std::endl;
	}
private:
	std::chrono::time_point<std::chrono::high_resolution_clock> m_StartTimepoint;

};

比较了三种方法创建指针的效率:

	{
		struct Vector2
		{
			float x, y;
		};
		{
			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::array<std::shared_ptr<Vector2>, 1000> sharedPtrs;
			Timer timer;
			for (int i = 0; i < sharedPtrs.size(); i++) {
				sharedPtrs[i] = std::shared_ptr<Vector2>();
			}
		}
		{
			std::array<std::unique_ptr<Vector2>, 1000> sharedPtrs;
			Timer timer;
			for (int i = 0; i < sharedPtrs.size(); i++) {
				sharedPtrs[i] = std::make_unique<Vector2>();
			}
		}

	}

结果是最后一种最快,第一种中间,第二种最慢,因为第三种unique指针效率最高,而第二种需要构造shared_ptr所以他效率最低。

相关推荐
软件黑马王子3 小时前
C#初级教程(4)——流程控制:从基础到实践
开发语言·c#
闲猫3 小时前
go orm GORM
开发语言·后端·golang
黑不溜秋的4 小时前
C++ 设计模式 - 策略模式
c++·设计模式·策略模式
李白同学4 小时前
【C语言】结构体内存对齐问题
c语言·开发语言
黑子哥呢?5 小时前
安装Bash completion解决tab不能补全问题
开发语言·bash
青龙小码农5 小时前
yum报错:bash: /usr/bin/yum: /usr/bin/python: 坏的解释器:没有那个文件或目录
开发语言·python·bash·liunx
大数据追光猿6 小时前
Python应用算法之贪心算法理解和实践
大数据·开发语言·人工智能·python·深度学习·算法·贪心算法
Dream it possible!6 小时前
LeetCode 热题 100_在排序数组中查找元素的第一个和最后一个位置(65_34_中等_C++)(二分查找)(一次二分查找+挨个搜索;两次二分查找)
c++·算法·leetcode
柠石榴6 小时前
【练习】【回溯No.1】力扣 77. 组合
c++·算法·leetcode·回溯
王老师青少年编程6 小时前
【GESP C++八级考试考点详细解读】
数据结构·c++·算法·gesp·csp·信奥赛