【发布时间】:2011-12-25 05:46:41
【问题描述】:
我无法理解以下内容,我希望有人能为我解释一下:
在 C++ 中,如果我创建一个包含 2M 不同文本位(testdata)的测试数据向量,然后使用这些字符串作为索引值创建一个映射,然后查找所有值,如下所示:
//Create test data
for(int f=0; f<loopvalue; f++)
{
stringstream convertToString;
convertToString << f;
string strf = convertToString.str();
testdata[f] = "test" + strf;
}
time_t startTimeSeconds = time(NULL);
for(int f=0; f<2000000; f++) testmap[ testdata[f] ] = f; //Write to map
for(int f=0; f<2000000; f++) result = testmap[ testdata[f] ]; //Lookup
time_t endTimeSeconds = time(NULL);
cout << "Time taken " << endTimeSeconds - startTimeSeconds << "seconds." << endl;
需要 10 秒。
如果我在 PHP 中看起来至少是一样的:
<?php
$starttime = time();
$loopvalue = 2000000;
//fill array
for($f=0; $f<$loopvalue; $f++)
{
$filler = "test" . $f;
$testarray[$filler] = $f;
}
//look up array
for($f=0; $f<$loopvalue; $f++)
{
$filler = "test" . $f;
$result = $testarray[$filler];
}
$endtime = time();
echo "Time taken ".($endtime-$starttime)." seconds.";
?>
...只需 3 秒。
鉴于 PHP 是用 C 编写的,有谁知道 PHP 如何实现这种更快的文本索引查找?
谢谢 C
【问题讨论】:
-
将字符串键映射切换到
std::unordered_map<std::string, int>并惊讶于差异。你可以对另一张地图做同样的事情,想想看。如果您没有该课程,请考虑std::tr1::unordered_map和<tr1/unordered_map>。 -
您对 C++ 代码使用了哪些编译器设置?尤其是哪个编译器和什么级别的优化?
-
result = testmap[ testdata[f] ] = f 是错字吗?
-
抱歉错字...已更正。
-
我只围绕查找移动了时间并使用了 unordered_map,果然它要快得多,PHP 和 C++ 之间的速度相同。我期待 C++ 更快。我正在使用 g++,我现在正在研究编译器优化。
标签: php c++ arrays performance map