【发布时间】:2017-09-29 14:50:17
【问题描述】:
我在 PHP 和带有 Boost 的 C++ 中都有以下实现。它只是将一个文件读入一个字符串,用空格分隔(我希望能够选择这个字符),然后在一个包含 2000 万个空格分隔的随机数(称为“空格”)的文件上运行:
在 PHP 中:
<?php
$a = explode(" ", file_get_contents("spaces"));
echo "Count: ".count($a)."\n";
foreach ($a as $b) {
echo $b."\n";
}
在 C++ 中:
#include <boost/algorithm/string.hpp>
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdio.h>
using namespace boost;
using namespace std;
int main(int argc, char* argv[])
{
// ifstream ifs("spaces");
// string s ((istreambuf_iterator<char>(ifs)), (istreambuf_iterator<char>()));
char * buffer = 0;
long length;
string filename = "spaces";
FILE * f = fopen (filename.c_str(), "rb");
if (f)
{
fseek (f, 0, SEEK_END);
length = ftell (f);
fseek (f, 0, SEEK_SET);
buffer = (char*) malloc (length);
if (buffer)
{
size_t t = fread (buffer, 1, length, f);
}
fclose (f);
}
string s(buffer, 0, length);
vector <string> v;
split(v, s, is_any_of(" "));
cout << "Count: " << v.size() << endl;
for (int i = 0; i < v.size(); i++) {
cout << v[i] << endl;
}
}
我用 g++ split.cpp -O2 -o split 编译它并在我的系统上持续运行它需要 4.5 秒,PHP7 需要 4.2 秒。 PHP 怎么能比 C++ 快 8%?
【问题讨论】:
-
这是我们无法回答的问题,因为过程中涉及许多变量——包括您当前的环境。我们只是猜测。
-
因为只有 8% 的代码? (jk,我不知道。)
-
关于您的 C++ 代码的一件事是您没有在
v中预先分配空间。如果您知道会有多少元素,那么您应该reserve那个空间,这将节省您当前方法所拥有的很多副本。 -
.3 秒对于这么小的测试来说并没有什么意义。这很容易通过缓存、I/O 活动或 CPU 活动来解释。
-
循环中的
endl可能也无济于事——大量不必要的刷新。
标签: php c++ performance boost