Ich muss mehrere C-Stil-Strings (um 500k) mit 4 Gleitkommazahlen durch ein einzelnes Leerzeichen getrennt analysieren. Es folgt ein Beispiel einer einzelnen Saite:Parse String von Zahlen
„90292 5879 89042,2576 5879“
Ich brauche diese Zahlen in zwei Strukturen zu speichern, die zwei Punkte. Wenn man bedenkt, dass die Zeichenkette während der Analyse geändert werden kann und dass 99,99% der Zahlen nur vorzeichenlose Ganzzahlen sind, was ist der schnellste Weg dazu?
Nach meiner aktuellen Implementierung ist:
#include <iostream>
#include <cassert>
#include <chrono>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
using namespace chrono;
struct PointF
{
float x;
float y;
};
void parse_points(char* points, PointF& p1, PointF& p2)
{
auto start = points;
const auto end = start + strlen(points);
// p1.x
start = std::find(start, end, ' ');
assert(start < end);
*start = '\0';
p1.x = static_cast<float>(atof(points));
points = start + 1;
// p1.y
start = std::find(start, end, ' ');
assert(start < end);
*start = '\0';
p1.y = static_cast<float>(atof(points));
points = start + 1;
// p2.x
start = std::find(start, end, ' ');
assert(start < end);
*start = '\0';
p2.x = static_cast<float>(atof(points));
points = start + 1;
// p2.y
start = std::find(start, end, ' ');
assert(start == end);
p2.y = static_cast<float>(atof(points));
}
int main()
{
const auto n = 500000;
char points_str[] = "90292 5879 89042.2576 5879";
PointF p1, p2;
vector<string> data(n);
for (auto& s : data)
s.assign(points_str);
const auto t0 = system_clock::now();
for (auto i = 0; i < n; i++)
parse_points(const_cast<char*>(data[i].c_str()), p1, p2);
const auto t1 = system_clock::now();
const auto elapsed = duration_cast<milliseconds>(t1 - t0).count();
cout << "Elapsed: " << elapsed << " ms" << endl;
cin.get();
return 0;
}
Ich denke 'boost :: lexical_cast' ist schneller als' atof'. –
@Sorosh_Sabz ist tatsächlich mehr als 8 Mal langsamer .... – Nick
Es gibt zu viele Parsing-Fragen, das Mindeste, was Sie tun können, ist, zuerst zu suchen. Probieren Sie Folgendes aus: ["stackoverflow C++ - Lesen von getrenntem Dateispeicher"] (https://www.google.com/search?q=stackoverflow+c%2B%2B+read+file+space+separated+float&ie=utf-8&oe = utf-8) –