使用C++-AMP来减少未排序向量搜索的运行时间

Using C++-AMP to reduce runtime of unsorted vector search

本文关键字:排序 向量搜索 运行时间 C++-AMP 使用      更新时间:2023-10-16

我编写了一个程序,该程序通过未排序的结构向量进行大量搜索,以找到唯一元素的索引。在for循环中,每次迭代都要进行多次搜索,而且在for循环迭代期间,向量内的数据也会多次更改(只添加数据,不删除任何数据)。现在这个程序做我想让它做的事情,但它相当慢,所以在我让VS2012分析我的程序的性能后,我发现程序80%以上的时间都在搜索未排序的向量,所以我自然想优化搜索。我知道我能得到的最好的是O(n),因为它是一个未排序的向量(每个元素都是唯一的,一旦插入,元素的顺序就不会改变),但我希望以某种方式减少运行时间。

我一直在考虑使用并行处理来减少程序运行时间,微软的AMP库看起来很有前景。从外观上看,您可以使用并行处理来遍历数组,以在数组中找到元素。但是未排序向量中的数据变化很大,所以这不会将瓶颈从迭代向量转移到从CPU到GPU的数据传输,或者AMP内置优化来应对这种情况吗?记住:矢量中的数据只添加在矢量的末尾,不会删除任何内容。

以防万一:这是矢量和我使用的搜索函数:

struct VertexData
{
    VertexData( unsigned int pos, unsigned int norm, unsigned int tex )
        : posIdx(pos), normIdx(norm), texIdx(tex) {}
    unsigned int posIdx;
    unsigned int normIdx;
    unsigned int texIdx;
    inline bool operator<( const VertexData &rhs ) const
    {
        return std::tie(posIdx, normIdx, texIdx) < std::tie(rhs.posIdx, rhs.normIdx, rhs.texIdx);
    }
    inline bool operator==( const VertexData &rhs ) const
    {
        return std::tie(posIdx, normIdx, texIdx) == std::tie(rhs.posIdx, rhs.normIdx, rhs.texIdx);
    }
};
std::vector<VertexData> verts;
int findIndex( const std::vector<VertexData> &vec, const VertexData &val ) const
{
    std::vector<VertexData>::const_iterator it;
    int idx = 0;
    for ( it = vec.begin(); it != vec.end(); ++it, ++idx )
        if ( *it == val )
            return idx;
    return -1;
}

您可以使用类似boost::multi-index数组的东西来为未排序的向量保存一组已排序的唯一索引吗?这样你就可以避免每次额外的工作。

通常,算法修复总是比暴力要好。