哈希表的性能,为什么C++最慢?

pac*_*tie 7 c++ perl hashtable go

对哈希进行简单的性能测试,看来C++版本比perl版本和golang版本都慢.

  • perl版本花了大约200毫秒,
  • C++版本需要280毫秒.
  • golang版本耗时56毫秒.

在我的PC上使用Core(TM)i7-2670QM CPU @ 2.20GHz,Ubuntu 14.04.3LTS,

有任何想法吗?

perl版本

use Time::HiRes qw( usleep ualarm gettimeofday tv_interval nanosleep
                      clock_gettime clock_getres clock_nanosleep clock
                      stat );
sub getTS {
    my ($seconds, $microseconds) = gettimeofday;
    return $seconds + (0.0+ $microseconds)/1000000.0;
}
my %mymap;
$mymap{"U.S."} = "Washington";
$mymap{"U.K."} = "London";
$mymap{"France"} = "Paris";
$mymap{"Russia"} = "Moscow";
$mymap{"China"} = "Beijing";
$mymap{"Germany"} = "Berlin";
$mymap{"Japan"} = "Tokyo";
$mymap{"China"} = "Beijing";
$mymap{"Italy"} = "Rome";
$mymap{"Spain"} = "Madrad";
$x = "";
$start = getTS();
for ($i=0; $i<1000000; $i++) {
    $x = $mymap{"China"};
}
printf "took %f sec\n", getTS() - $start;
Run Code Online (Sandbox Code Playgroud)

C++版

#include <iostream>
#include <string>
#include <unordered_map>
#include <sys/time.h>

double getTS() {
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return tv.tv_sec + tv.tv_usec/1000000.0;
}
using namespace std;
int main () {
  std::unordered_map<std::string,std::string> mymap;

  // populating container:
    mymap["U.S."] = "Washington";
    mymap["U.K."] = "London";
    mymap["France"] = "Paris";
    mymap["Russia"] = "Moscow";
    mymap["China"] = "Beijing";
    mymap["Germany"] = "Berlin";
    mymap["Japan"] = "Tokyo";
    mymap["China"] = "Beijing";
    mymap["Italy"] = "Rome";
    mymap["Spain"] = "Madrad";  

  double start = getTS();
  string x;
  for (int i=0; i<1000000; i++) {
      mymap["China"];
  }
  printf("took %f sec\n", getTS() - start);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

Golang版

package main

import "fmt"
import "time"

func main() {
    var x string
    mymap := make(map[string]string)
    mymap["U.S."] = "Washington";
    mymap["U.K."] = "London";
    mymap["France"] = "Paris";
    mymap["Russia"] = "Moscow";
    mymap["China"] = "Beijing";
    mymap["Germany"] = "Berlin";
    mymap["Japan"] = "Tokyo";
    mymap["China"] = "Beijing";
    mymap["Italy"] = "Rome";
    mymap["Spain"] = "Madrad";
    t0 := time.Now()
    sum := 1
    for sum < 1000000 {
        x = mymap["China"]
        sum += 1
    }
    t1 := time.Now()
    fmt.Printf("The call took %v to run.\n", t1.Sub(t0))
    fmt.Println(x)
}
Run Code Online (Sandbox Code Playgroud)

更新1

为了提高C++版本,改x = mymap["China"];mymap["China"];,但在性能上只有细微的差别.

更新2

在没有任何优化的情况下编译时我得到了原始结果:g++ -std=c++11 unorderedMap.cc.通过"-O2"优化,它只花费大约一半的时间(150毫秒)

更新3

为了删除可能char*string构造函数调用,我创建了一个字符串常量.时间缩短到大约220ms(编译时没有优化).感谢来自@ neil-kirk的建议,通过优化(-O2标志),时间大约是80ms.

  double start = getTS();
  string x = "China";
  for (int i=0; i<1000000; i++) {
      mymap[x];
  }
Run Code Online (Sandbox Code Playgroud)

更新4

感谢@ steffen-ullrich,他指出perl版本存在语法错误.我换了它.性能数字约为150毫秒.

更新5

看来执行指令的数量很重要.使用命令valgrind --tool=cachegrind <cmd>

对于Go版本

$ valgrind --tool=cachegrind  ./te1
==2103== Cachegrind, a cache and branch-prediction profiler
==2103== Copyright (C) 2002-2013, and GNU GPL'd, by Nicholas Nethercote et al.
==2103== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info
==2103== Command: ./te1
==2103== 
--2103-- warning: L3 cache found, using its data for the LL simulation.
The call took 1.647099s to run.
Beijing
==2103== 
==2103== I   refs:      255,763,381
==2103== I1  misses:          3,709
==2103== LLi misses:          2,743
==2103== I1  miss rate:        0.00%
==2103== LLi miss rate:        0.00%
==2103== 
==2103== D   refs:      109,437,132  (77,838,331 rd   + 31,598,801 wr)
==2103== D1  misses:        352,474  (   254,714 rd   +     97,760 wr)
==2103== LLd misses:        149,260  (    96,250 rd   +     53,010 wr)
==2103== D1  miss rate:         0.3% (       0.3%     +        0.3%  )
==2103== LLd miss rate:         0.1% (       0.1%     +        0.1%  )
==2103== 
==2103== LL refs:           356,183  (   258,423 rd   +     97,760 wr)
==2103== LL misses:         152,003  (    98,993 rd   +     53,010 wr)
==2103== LL miss rate:          0.0% (       0.0%     +        0.1%  )
Run Code Online (Sandbox Code Playgroud)

对于C++优化版本(无优化标志)

$ valgrind --tool=cachegrind ./a.out
==2180== Cachegrind, a cache and branch-prediction profiler
==2180== Copyright (C) 2002-2013, and GNU GPL'd, by Nicholas Nethercote et al.
==2180== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info
==2180== Command: ./a.out
==2180== 
--2180-- warning: L3 cache found, using its data for the LL simulation.
took 64.657681 sec
==2180== 
==2180== I   refs:      5,281,474,482
==2180== I1  misses:            1,710
==2180== LLi misses:            1,651
==2180== I1  miss rate:          0.00%
==2180== LLi miss rate:          0.00%
==2180== 
==2180== D   refs:      3,170,495,683  (1,840,363,429 rd   + 1,330,132,254 wr)
==2180== D1  misses:           12,055  (       10,374 rd   +         1,681 wr)
==2180== LLd misses:            7,383  (        6,132 rd   +         1,251 wr)
==2180== D1  miss rate:           0.0% (          0.0%     +           0.0%  )
==2180== LLd miss rate:           0.0% (          0.0%     +           0.0%  )
==2180== 
==2180== LL refs:              13,765  (       12,084 rd   +         1,681 wr)
==2180== LL misses:             9,034  (        7,783 rd   +         1,251 wr)
==2180== LL miss rate:            0.0% (          0.0%     +           0.0%  )
Run Code Online (Sandbox Code Playgroud)

适用于C++优化版

$ valgrind --tool=cachegrind ./a.out
==2157== Cachegrind, a cache and branch-prediction profiler
==2157== Copyright (C) 2002-2013, and GNU GPL'd, by Nicholas Nethercote et al.
==2157== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info
==2157== Command: ./a.out
==2157== 
--2157-- warning: L3 cache found, using its data for the LL simulation.
took 9.419447 sec
==2157== 
==2157== I   refs:      1,451,459,660
==2157== I1  misses:            1,599
==2157== LLi misses:            1,549
==2157== I1  miss rate:          0.00%
==2157== LLi miss rate:          0.00%
==2157== 
==2157== D   refs:        430,486,197  (340,358,108 rd   + 90,128,089 wr)
==2157== D1  misses:           12,008  (     10,337 rd   +      1,671 wr)
==2157== LLd misses:            7,372  (      6,120 rd   +      1,252 wr)
==2157== D1  miss rate:           0.0% (        0.0%     +        0.0%  )
==2157== LLd miss rate:           0.0% (        0.0%     +        0.0%  )
==2157== 
==2157== LL refs:              13,607  (     11,936 rd   +      1,671 wr)
==2157== LL misses:             8,921  (      7,669 rd   +      1,252 wr)
==2157== LL miss rate:            0.0% (        0.0%     +        0.0%  )
Run Code Online (Sandbox Code Playgroud)

Ste*_*ich 16

从您的Perl代码(在您尝试修复它之前):

@mymap = ();
$mymap["U.S."] = "Washington";
$mymap["U.K."] = "London";
Run Code Online (Sandbox Code Playgroud)

这不是地图而是数组.哈希映射的语法是:

  %mymap;
  $mymap{"U.S."} = ....
Run Code Online (Sandbox Code Playgroud)

因此,您有效地做的是创建一个数组而不是哈希映射并始终访问元素0.请使用use strict;use warnings;Perl的所有时间,甚至带警告的简单语法检查都会向您显示问题:

perl -cw x.pl
Argument "U.S." isn't numeric in array element at x.pl line 9.
Argument "U.K." isn't numeric in array element at x.pl line 10.
Run Code Online (Sandbox Code Playgroud)

除此之外,基准测试的主要部分实际上没有任何用处(分配变量并且从不使用它),并且一些编译器可以检测它并简单地优化它.

如果您要检查Perl程序生成的代码,您会看到:

$ perl -MO=Deparse x.pl
@mymap = ();
$mymap[0] = 'Washington';
$mymap[0] = 'London';
...
for ($i = 0; $i < 1000000; ++$i) {
    $x = $mymap[0];
}
Run Code Online (Sandbox Code Playgroud)

也就是说,它在编译时检测到问题,并将其替换为对数组索引0的访问.

因此,无论何时基准测试,您需要:

  • 检查你的程序是否真正实现了它应该做的事情.
  • 检查编译器是否没有优化,不会在编译时执行其他语言在运行时执行的操作.任何没有或可预测结果的陈述都倾向于这种优化.
  • 确认您实际测量的是您要测量的内容,而不是其他内容.即使对程序进行微小的更改也会影响运行时间,因为需要的内存分配不是之前等等,这些更改可能与您要测量的内容无关.在您的基准测试中,您可以反复测量对同一哈希元素的访问权限,而无需访问其中的其他元素.这是一个可以在处理器缓存中发挥很好的活动,但可能无法反映实际使用情况.

并且,使用简单的计时器不是一个现实的基准.系统上还有其他进程,有调度程序,有缓存垃圾......而且今天的CPU很大程度上取决于系统上的负载,因为CPU可能会在低功耗模式下运行一个基准测试而不是其他基准测试,即使用不同的CPU时钟.例如,相同"基准"的多次运行在我的系统上在100ms和150ms之间的测量时间内变化.

基准测试是谎言,微观基准测试就像你的一样.

  • @codingFun:正如您所看到的,在进行细微更改时,性能会有很大差异.只需从`$ x = $ mymap {..}`到`my $ x = $ mymap {...}`进行简单的更改,就会显着影响性能.在我的系统上,程序的多次运行之间存在50%的差异. (2认同)

Jam*_*one 2

这是一个猜测:

unordered_map::operator[] 需要一个字符串参数。您正在提供一个 char*。如果不进行优化,C++ 版本可能会调用 std::string(char*) 构造函数一百万次,以便将“China”转换为 std::string。Go 的语言规范可能使“字符串文字”与字符串类型相同,因此不需要调用构造函数。

启用优化后,字符串构造函数将被提升到循环之外,您将不会看到相同的问题。或者很可能除了获取时间的两个系统调用和打印差异的系统调用之外不会生成任何代码,因为最终这一切都没有效果。

为了确认这一点,您必须实际查看正在生成的程序集。这将是一个编译器选项。请参阅问题了解 GCC 所需的标志。