对 hash 进行了一个简单的性能测试,看起来 C++ 版本比 perl 版本和 golang 版本都慢。
perl 版本用了大约 200 毫秒,
C++ 版本用了 280 毫秒。
golang 版本用了 56 毫秒。
在我的带有 Core(TM) i7-2670QM CPU @ 2.20GHz、Ubuntu 14.04.3LTS 的 PC 上,
有任何想法吗?
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;
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;
}
达令说
缥缈止盈
潇湘沐
相关分类