简体   繁体   English

C#Hashtable与C ++ hash_map

[英]C# Hashtable vs c++ hash_map

I'm comparing the following code in C++ and C# and C# (Mono 2.4) seems to be faster. 我在C ++和C#中比较以下代码,而C#(Mono 2.4)似乎更快。 Is there anything wrong with the C++ code? C ++代码有什么问题吗?

 #include <map>
 #include <string>
 #include <iostream>
 #include <ext/hash_map>
 #include <boost/any.hpp>

 int main()
 {
    //std::map<long, long> m;
    // hash_map is a little bit faster
    __gnu_cxx::hash_map<long, long> m;

    for( long i = 0; i < 1000000; ++i )
    {
        m[i]  = i;
    }

 }

And C# 和C#

 using System;
 using System.Collections;

 public int Main()
 {
     Hashtable m = new Hashtable();

     for( long i = 0; i < 1000000; ++i )
     {
        m[i]  = i;
     }

}

C# code is actually twice as fast on the same machine. 实际上,C#代码在同一台计算机上的速度是其两倍。

$ time ./a.out

real    0m1.028s
user    0m0.986s
sys     0m0.041s

$ time mono test.exe

real    0m0.603s
user    0m0.732s
sys     0m0.090s

You need to compile the C++ code with compiler optimizations turned on for a fair comparison. 您需要在编译器优化处于打开状态的情况下编译C ++代码,以便进行合理的比较。 Otherwise, you are comparing apples to debug builds — the compiler will not even try to emit fast code. 否则,您会将苹果与调试版本进行比较-编译器甚至不会尝试发出快速代码。

In GCC this would be the -O3 flag, to start with. 在GCC中,首先是-O3标志。

Some thoughts: 一些想法:

  • You're comparing Mono against Boost 您正在将Mono与Boost进行比较
  • Which optimization (default or not) settings did you use for Mono and C++ ? 您对Mono和C ++使用了哪些优化设置(默认设置)?
  • What are the initial / default hash table sizes for the C# and C++ versions ? C#和C ++版本的初始/默认哈希表大小是多少?
  • Have you tried comparing against other C++ hash maps, such as the sparse hash table ? 您是否尝试过与其他C ++ 哈希表 (例如稀疏哈希表)进行比较
  • Remember not only to look at real time, but actual CPU time used. 请记住,不仅要查看实时信息 ,还要记住实际使用的CPU时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM