【问题标题】:Fast C++ container like the C# HashSet<T> and Dictionary<K,V>?像 C# HashSet<T> 和 Dictionary<K,V> 这样的快速 C++ 容器?
【发布时间】:2010-11-06 13:57:54
【问题描述】:

我在 C# 中使用过很多 HashSet 和 Dictionary,发现它们的速度非常快......

我尝试过使用 std::map 和 std::hash_map 并且发现它们比较慢。这听起来像预期的行为吗?我在使用 std::hash_map 时可能做错了什么?

或者,有没有更好的 C++ Hash 容器?

我正在散列 int32,通常大约 100,000 个。

更新:我用 C# 和 C++ 创建了一个 repro。它运行了两次试验,它们在 C# 中需要 19 毫秒和 13 毫秒,在 C++ 中大约需要 11,000 毫秒。我的 C++ 代码一定有什么问题:)

(两者都作为发布版本运行,都是控制台应用程序)

C# 输出:

Found 511 values in the intersection, in 19 ms
Found 508 values in the intersection, in 13 ms

C++ 输出:

Found 308 values in the intersection, in 11764.7ms
Found 316 values in the intersection, in 11742.8ms

C++ 输出(使用 stdext::hash_map 代替 std::map)

Found 300 values in the intersection, in 383.552ms
Found 306 values in the intersection, in 2277.02ms

C++ 输出(使用 stdext::hash_map,x64 版本)

Found 292 values in the intersection, in 1037.67ms
Found 302 values in the intersection, in 3663.71ms

注意事项:

  • Set2 没有像我在 C++ 中想要的那样被填充,我希望它与 Set1 有 50% 的交集(就像在 C# 中一样),但出于某种原因我不得不将我的随机数乘以 10让它们部分不相交

C#:

    static void Main(string[] args)
    {
        int start = DateTime.Now.Millisecond;
        int intersectionSize = runIntersectionTest();
        int duration = DateTime.Now.Millisecond - start;

        Console.WriteLine(String.Format("Found {0} values in the intersection, in {1} ms", intersectionSize, duration));

        start = DateTime.Now.Millisecond;
        intersectionSize = runIntersectionTest();
        duration = DateTime.Now.Millisecond - start;

        Console.WriteLine(String.Format("Found {0} values in the intersection, in {1} ms", intersectionSize, duration));

        Console.ReadKey();
    }

    static int runIntersectionTest()
    {
        Random random = new Random(DateTime.Now.Millisecond);

        Dictionary<int,int> theMap = new Dictionary<int,int>();

        List<int> set1 = new List<int>();
        List<int> set2 = new List<int>();

        // Create 100,000 values for set1
        for ( int i = 0; i < 100000; i++ )
        {
            int value = 1000000000 + i;
            set1.Add(value);
        }

        // Create 1,000 values for set2
        for ( int i = 0; i < 1000; i++ )
        {
            int value = 1000000000 + (random.Next() % 200000 + 1);
            set2.Add(value);
        }

        // Now intersect the two sets by populating the map
        foreach( int value in set1 )
        {
            theMap[value] = 1;
        }

        int intersectionSize = 0;

        foreach ( int value in set2 )
        {
            int count;
            if ( theMap.TryGetValue(value, out count ) )
            {
                intersectionSize++;
                theMap[value] = 2;
            }
        }

        return intersectionSize;
    }

C++:

int runIntersectionTest()
{
    std::map<int,int> theMap;

    vector<int> set1;
    vector<int> set2;

    // Create 100,000 values for set1
    for ( int i = 0; i < 100000; i++ )
    {
        int value = 1000000000 + i;
        set1.push_back(value);
    }

    // Create 1,000 values for set2
    for ( int i = 0; i < 1000; i++ )
    {
        int random = rand() % 200000 + 1;
        random *= 10;

        int value = 1000000000 + random;
        set2.push_back(value);
    }

    // Now intersect the two sets by populating the map
    for ( vector<int>::iterator iterator = set1.begin(); iterator != set1.end(); iterator++ )
    {
        int value = *iterator;

        theMap[value] = 1;
    }

    int intersectionSize = 0;

    for ( vector<int>::iterator iterator = set2.begin(); iterator != set2.end(); iterator++ )
    {
        int value = *iterator;

        map<int,int>::iterator foundValue = theMap.find(value);

        if ( foundValue != theMap.end() )
        {
            theMap[value] = 2;

            intersectionSize++;
        }
    }

    return intersectionSize;

}

int _tmain(int argc, _TCHAR* argv[])
{
    srand ( time(NULL) );

    Timer timer;
    int intersectionSize = runIntersectionTest();
    timer.Stop();

    cout << "Found " << intersectionSize << " values in the intersection, in " << timer.GetMilliseconds() << "ms" << endl;

    timer.Reset();
    intersectionSize = runIntersectionTest();
    timer.Stop();

    cout << "Found " << intersectionSize << " values in the intersection, in " << timer.GetMilliseconds() << "ms" << endl;

    getchar();

    return 0;
}

【问题讨论】:

  • 你能提供一些基准吗?
  • 在 C# 中可能需要 10 毫秒,在 C++ 中似乎需要 1,000 毫秒。明天我会尝试做一个更可控的比较,可能会发布每个 C# 和 C++ 的代码。
  • @Alex:虽然我对 Visual Studio 的内部细节还不够熟悉,但听起来问题出在调试器正在添加的工具上,而不是在编译器生成的代码中. 100 倍的减速肯定是一个错误。举报!
  • @David:感谢您的参与。我们设法查明了这一点,请参阅:stackoverflow.com/questions/1060337/…。当您附加调试器时,会发生使用不同 (DEBUG) 内存堆的情况 - 您可以根据需要将其关闭。

标签: c++ hashtable hashmap


【解决方案1】:

Hash_map 和 hash_set 是非标准的,unordered_mapunordered_set 最有可能很快成为标准版本。如果没有复制器,我认为这不会走得太远。在底层,它们是相同的数据结构,因此它们应该具有相似的性能。


我在 MS Visual Studio 2008 v9.0.30729.1 下将提供的示例编译为 Visual C++ -> Win32 -> 控制台应用程序(尽管我推出了自己的 Timer 类,因为我不确定您使用的是什么)。在调试下,我得到了 1000 毫秒的时间,但在发布下编译是 50 毫秒。

#include <vector>
#include <iostream>
#include <map>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#include <windows.h>

typedef struct {
    LARGE_INTEGER start;
    LARGE_INTEGER stop;
} stopWatch;

class CStopWatch {

private:
    stopWatch timer;
    LARGE_INTEGER frequency;
    double LIToSecs( LARGE_INTEGER & L);
public:
    CStopWatch();
    void startTimer( );
    void stopTimer( );
    double getElapsedTime();
};

double CStopWatch::LIToSecs( LARGE_INTEGER & L) {
    return ((double)L.QuadPart /(double)frequency.QuadPart) ;
}

CStopWatch::CStopWatch(){
    timer.start.QuadPart=0;
    timer.stop.QuadPart=0;
    QueryPerformanceFrequency( &frequency ) ;
}

void CStopWatch::startTimer( ) {
    QueryPerformanceCounter(&timer.start) ;
}

void CStopWatch::stopTimer( ) {
    QueryPerformanceCounter(&timer.stop) ;
}

double CStopWatch::getElapsedTime() {
    LARGE_INTEGER time;
    time.QuadPart = timer.stop.QuadPart - timer.start.QuadPart;
    return LIToSecs( time) ;
}

using namespace std;
int runIntersectionTest()
{
    std::map<int,int> theMap;

    vector<int> set1;
    vector<int> set2;

    // Create 100,000 values for set1
    for ( int i = 0; i < 100000; i++ )
    {
        int value = 1000000000 + i;
        set1.push_back(value);
    }

    // Create 1,000 values for set2
    for ( int i = 0; i < 1000; i++ )
    {
        int random = rand() % 200000 + 1;
        random *= 10;

        int value = 1000000000 + random;
        set2.push_back(value);
    }

    // Now intersect the two sets by populating the map
    for ( vector<int>::iterator iterator = set1.begin(); iterator != set1.end(); iterator++ )
    {
        int value = *iterator;

        theMap[value] = 1;
    }

    int intersectionSize = 0;

    for ( vector<int>::iterator iterator = set2.begin(); iterator != set2.end(); iterator++ )
    {
        int value = *iterator;

        map<int,int>::iterator foundValue = theMap.find(value);

        if ( foundValue != theMap.end() )
        {
                theMap[value] = 2;

                intersectionSize++;
        }
    }

    return intersectionSize;

}

int main(int argc, char* argv[])
{
    srand ( time(NULL) );
    int tests = 2;
    while(tests--){
      CStopWatch timer;
      timer.startTimer();
      int intersectionSize = runIntersectionTest();
      timer.stopTimer();

      cout << "Found " << intersectionSize << " values in the intersection, in " << timer.getElapsedTime() << "s\r\n";
    }

    getchar();

    return 0;
}

(我会尝试使用 unordered_map,但我的版本没有)。我怀疑你的 C++ 设置有问题。

【讨论】:

  • 注意:boost 提供了两者的实现。
  • 我想通了:如果我将调试器附加到 RELEASE 或 DEBUG 构建(例如,在 IDE 中按 F5),那么我会遇到可怕的情况。
【解决方案2】:

我们设法找到了真相,请参阅:

Why does my STL code run so slowly when I have the debugger/IDE attached?

当您附加调试器时会使用不同的 (DEBUG) 内存堆 - 您可以根据需要将其关闭。

【讨论】:

    【解决方案3】:

    这听起来并不出人意料,但您需要收集更多详细信息,然后我们才能真正提供帮助。你在使用谁的 hash_map 实现?您是否将分析器指向它,如果是,它告诉您什么?

    一般来说,如果哈希表实现没有明显的原因表现不佳,通常是因为表使用的哈希函数恰好对您的特定输入执行不佳。这可能是你的问题 - C++ hash_map 碰巧使用了一个哈希函数,将你的键映射到一小部分桶,而 C# HashSet 没有 - 或者它可能完全不同。

    std::map 通常以树的形式实现,因此会有不同的性能特征。同样,实现细节和输入数据很重要。

    【讨论】:

    • 当我使用 hash_map 时,我相信我使用的是 Microsoft 的...我刚刚启动了 VS 2008 并输入了#include 。关于 Int32 数字的 hash_map 的良好哈希函数的任何提示?我会做一些谷歌搜索。
    • VC++ 团队对 IME 这类事情非常敏锐,这让我认为它不太可能是哈希函数问题。明天你发布示例代码后,我会更深入地研究这个问题。
    【解决方案4】:

    我从未使用过,但 Google Sparcehash 可能很合适

    【讨论】:

      【解决方案5】:

      您在 C++ 代码中使用 std::map,它的插入和查找时间为 O(log(n))。尝试使用 hash_map 进行测试以获得更好的比较。

      【讨论】:

      • 我将 std::map 切换为 stdext::hash_map,得到了更好的结果,但与 C# 相比仍然很糟糕。在交叉路口找到 300 个值,用时 383.552ms 在交叉路口找到 306 个值,用时 2277.02ms
      【解决方案6】:

      你真正比较的是

      O(1) 的 C# 哈希集,意味着几乎恒定且与输入大小无关,

      相对于 C++ 向量....意思是(输入的大小)乘以常数...

      这没有什么实际意义。

      您应该尝试在 C++ 中使用等效的 hashset (我认为是在 2007 年的 tr1 之后) std::tr1::unordered_set<...> (和 std::tr1::unordered_set<...>)

      wikipedia link on TR1

      还要注意,根据this page,Visual Studio 有自己的次优 stl tr1 实现。 (没有亲身经历,找到了here

      【讨论】:

        猜你喜欢
        • 2014-06-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-16
        • 2010-09-21
        • 1970-01-01
        • 1970-01-01
        • 2014-04-03
        相关资源
        最近更新 更多