I'm absolutely dumbfounded by this. I was trying to demonstrate to myself how much faster C++ is than even modern PHP. I ran a simple CSV parsing program in both that have the same output. The CSV file is 40,194,684 parsed down to 1,537,194 lines.
EDIT: This sparked alot more conversation than I had anticipated, here's the hardware stats for the machine both programs were run on, however its actually a VM running on a nutanix server: CPU: Intel(R) Xeon(R) Silver 4215R CPU @ 3.20GHz RAM: 16GB
PHP code (runtime 42.750 s):
<?php
$i_fp = fopen("inFile.csv","r");
$o_fp = fopen("outFile.csv","w");
while(!feof($i_fp))
{
$line = fgets($i_fp);
$split = explode(';',$line);
if($split[3] == 'E' || $split[3] == 'T')
{
fwrite($o_fp,join(',',[ $split[0], $split[1], $split[3], $split[4], $split[5], $split[6],
$split[10], $split[9],$split[11],$split[7],$split[32]])."\n");
}
}
fclose($i_fp);
fclose($o_fp);
C++ code (runtime 3 m 59.074s) (compiled using g++ parse.cpp -o parse -O2 -std=c++1y
)
#include <fstream>
#include <stdlib.h>
#include <string>
#include <vector>
using std::string;
using std::vector;
vector<string> splitStr(string line, const char delimiter = ',')
{
vector<string> splitLine;
string buf;
for(size_t i=0; i<line.length(); i++)
{
if(line[i] == delimiter)
{
splitLine.push_back(buf);
buf.clear();
}else{
buf += line[i];
}
}
return splitLine;
}
string makeCSVLine(vector<string> splitLine)
{
string line =
splitLine[0] + ',' +
splitLine[1] + ',' +
splitLine[3] + ',' +
splitLine[4] + ',' +
splitLine[5] + ',' +
splitLine[6] + ',' +
splitLine[10] + ',' +
splitLine[9] + ',' +
splitLine[11] + ',' +
splitLine[7] + ',' +
splitLine[32] + '\n';
return line;
}
int main(int argc, char* argv[])
{
if(argc < 3)
{
exit(EXIT_SUCCESS);
}
string inPath = argv[1];
string outPath = argv[2];
std::ifstream inFile;
std::ofstream outFile;
inFile.open(inPath.c_str());
outFile.open(outPath.c_str());
string line;
while(std::getline(inFile,line))
{
vector<string> split = splitStr(line, ';');
if(split[3][0] == 'E' || split[3][0] == 'T')
{
outFile << makeCSVLine(split);
}
}
inFile.close();
outFile.close();
}
Both running on Red Hat Linux 8. I'm sure that it's some mistake I'm making in terms of C++ efficiency (possibly somewhere in how I'm using string
s and vector
s and whether they need to be re-sized repeatedly per loop), but I'm not sure what it could be. If anyone could help, shed some light. That would be great.
EDIT: Unfortunately, I cannot provide the input file as its a sensitive internal file.
Thanks to everyone for taking so much interest in this and all the advice provided. I've been extremely busy at work lately and unable to re-visit but look forward to doing so soon.