Trovo risultati piuttosto diversi utilizzando clang++ -O3 -std=c++11 -stdlib=libc++
.
In primo luogo ho estratto un file di testo con ~ parole 470K separate da virgole, senza ritorni a capo in una stringa gigante, in questo modo:
path const inputPath("input.txt");
filebuf buf;
buf.open(inputPath.string(),ios::in);
if (!buf.is_open())
return cerr << "can't open" << endl, 1;
string str(filesystem::file_size(inputPath),'\0');
buf.sgetn(&str[0], str.size());
buf.close();
Poi ho eseguito vari test cronometrati memorizzare i risultati in un vettore di pre-sized eliminato tra le esecuzioni, per esempio,
void vectorStorage(string const& str)
{
static size_t const expectedSize = 471785;
vector<string> contents;
contents.reserve(expectedSize+1);
...
{
timed _("split is_any_of");
split(contents, str, is_any_of(","));
}
if (expectedSize != contents.size()) throw runtime_error("bad size");
contents.clear();
...
}
per riferimento, il timer è proprio questo:
struct timed
{
~timed()
{
auto duration = chrono::duration_cast<chrono::duration<double, ratio<1,1000>>>(chrono::high_resolution_clock::now() - start_);
cout << setw(40) << right << name_ << ": " << duration.count() << " ms" << endl;
}
timed(std::string name="") :
name_(name)
{}
chrono::high_resolution_clock::time_point const start_ = chrono::high_resolution_clock::now();
string const name_;
};
Ho anche eseguito il clock di una singola iterazione (nessun vettore). Ecco i risultati:
Vector:
hand-coded: 54.8777 ms
split is_any_of: 67.7232 ms
split is_from_range: 49.0215 ms
tokenizer: 119.37 ms
One iteration:
tokenizer: 97.2867 ms
split iterator: 26.5444 ms
split iterator back_inserter: 57.7194 ms
split iterator char copy: 34.8381 ms
Il tokenizzatore è tanto più lento rispetto split
, la figura di un iterazione non include anche la copia stringa:
{
string word;
word.reserve(128);
timed _("tokenizer");
boost::char_separator<char> sep(",");
boost::tokenizer<boost::char_separator<char> > tokens(str, sep);
for (auto range : tokens)
{}
}
{
string word;
timed _("split iterator");
for (auto it = make_split_iterator(str, token_finder(is_from_range(',', ',')));
it != decltype(it)(); ++it)
{
word = move(copy_range<string>(*it));
}
}
conclusione univoca: utilizzare split
.
Profile it and you tell. –
Il secondo sembra non avere alcuna allocazione di memoria, quindi immagino che sarà più veloce. C'è solo un modo per essere sicuro, però. –
[Boost.Spirit] (http://www.boost.org/libs/spirit/). [Qi] (http://www.boost.org/libs/spirit/doc/html/spirit/qi/tutorials /quick_start.html) supererà entrambi con un ampio margine. – ildjarn