gpt4 book ai didi

c# - 树结构的 C++ API 性能问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:50:29 24 4
gpt4 key购买 nike

我正在为 C++ 模拟框架编写 API。我想在 C# 中使用这个 API。但是我在获取模拟中所有角色的位置时遇到了性能问题。我试图向您详细解释该框架的工作原理。

有一个模拟器类:

class Simulator
{
/// A list of the characters that are currently in the simulation.
std::vector<Character> characters;
/// A list of the path planning results for the characters currently in the simulation.
std::vector<PathPlanningResult*> pathPlanningResults;
/// A mapping from character IDs (which can be set externally) to their positions in the 'characters' and 'PathPlanningResults' lists (which always number from 0).
std::map<int, int> characterVectorPositions;

/** Finds and returns a pointer to the character with the specified ID.
* @param id The ID of the character to find.
* @return A pointer to the Character object that matches the given ID, or NULL if no such character exists.
*/
inline Character* getCharacter(int id)
{
std::map<int,int>::iterator findIt = characterVectorPositions.find(id);
if(findIt == characterVectorPositions.end()) return NULL;
return &characters[findIt->second];
}

/// Adds a character to the simulation, with the specified settings.
bool Simulator::addCharacter(const Point& pos, short layer, const CharacterSettings& settings, int id)
{
Character newCharacter(id, pos, layer, settings);

// add the character
characters.push_back(newCharacter);
// add an empty result
pathPlanningResults.push_back(NULL);
// add the ID mapping
characterVectorPositions.insert(std::pair<int,int>(id, characters.size()-1));
}
}

这个类包含模拟中的所有角色对象。

有一个带有获取位置方法的字符类:

class Character
{
/** Returns the current 2D position of the character on its current layer.
* @return The current position of the character.
*/
inline const Point& getPosition() const { return pos; }
}

Point 对象包含 X 和 Y 坐标

还有一个 API 类 API_simulator,它有两种获取角色位置的方法:

class API_simulator 
{
extern "C" EXPORT_API double GetCharacterX(int charid) {
return simulator->getCharacter(charid)->getPosition().x;
}

extern "C" EXPORT_API double GetCharacterY(int charid) {
return simulator->getCharacter(charid)->getPosition().y;
}
}

当我在 C# 中使用此 API 时,一切正常。除非我向模拟器添加了很多角色并且我需要获取所有角色的位置。这需要很长时间,因为必须在树结构中找到每个字符的每个 X 和 Y 坐标。有没有更快的方法一次性获取所有角色的位置?共享内存是解决方案吗?

最佳答案

我不认为 map 是瓶颈。它应该具有足够的可扩展性,因此通过 map 查找每个字符的信息应该足够快,即使有几千个字符(这会导致 10 到 15 次查找)。
但是,如果您想要所有字符的坐标,最好立即迭代正确的 vector ,而不是通过每个字符的 id 查找偏移量。

关于c# - 树结构的 C++ API 性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16692180/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com