Эти результаты относятся только к компилятору Linux или Cygwin. Если вы используете Visual Studio Compiler
, результаты для std::getline
и std::ifstream.getline
будут 100%
или более медленными, чем встроенный итератор Python for line in file
.
Вы увидите, что linecache.push_back( emtpycacheobject )
используется в коде, потому что таким образом я только сравниваю время, используемое для чтения строк, исключая время, которое Python тратит на преобразование входной строки в объект Unicode Python. Поэтому я закомментировал все строки, которые вызывают PyUnicode_DecodeUTF8
.
Это глобальные определения, используемые в примерах:
const char* filepath = "./myfile.log";
size_t linecachesize = 131072;
PyObject* emtpycacheobject;
emtpycacheobject = PyUnicode_DecodeUTF8( "", 0, "replace" );
Мне удалось оптимизировать использование Posix C getline
(кэшируя общий размер буфера вместо того, чтобы всегда передавать 0), и теперь Posix C getline
превосходит встроенную Python for line in file
на 5%
. Я предполагаю, что если я удаляю весь код Python и C ++ вокруг Posix C getline
, это должно повысить производительность:
char* readline = (char*) malloc( linecachesize );
FILE* cfilestream = fopen( filepath, "r" );
if( cfilestream == NULL ) {
std::cerr << "ERROR: Failed to open the file '" << filepath << "'!" << std::endl;
}
if( readline == NULL ) {
std::cerr << "ERROR: Failed to alocate internal line buffer!" << std::endl;
}
bool getline() {
ssize_t charsread;
if( ( charsread = getline( &readline, &linecachesize, cfilestream ) ) != -1 ) {
fileobj.getline( readline, linecachesize );
// PyObject* pythonobject = PyUnicode_DecodeUTF8( readline, charsread, "replace" );
// linecache.push_back( pythonobject );
// return true;
Py_XINCREF( emtpycacheobject );
linecache.push_back( emtpycacheobject );
return true;
}
return false;
}
if( readline ) {
free( readline );
readline = NULL;
}
if( cfilestream != NULL) {
fclose( cfilestream );
cfilestream = NULL;
}
Мне также удалось улучшить производительность C ++ до 20%
медленнее, чем встроенный Python C for line in file
, с помощью std::ifstream.getline()
:
char* readline = (char*) malloc( linecachesize );
std::ifstream fileobj;
fileobj.open( filepath );
if( fileobj.fail() ) {
std::cerr << "ERROR: Failed to open the file '" << filepath << "'!" << std::endl;
}
if( readline == NULL ) {
std::cerr << "ERROR: Failed to alocate internal line buffer!" << std::endl;
}
bool getline() {
if( !fileobj.eof() ) {
fileobj.getline( readline, linecachesize );
// PyObject* pyobj = PyUnicode_DecodeUTF8( readline, fileobj.gcount(), "replace" );
// linecache.push_back( pyobj );
// return true;
Py_XINCREF( emtpycacheobject );
linecache.push_back( emtpycacheobject );
return true;
}
return false;
}
if( readline ) {
free( readline );
readline = NULL;
}
if( fileobj.is_open() ) {
fileobj.close();
}
Наконец, мне также удалось получить только на 10%
меньшую производительность, чем встроенный Python C for line in file
с std::getline
, кэшировав std::string
, который он использует в качестве ввода:
std::string line;
std::ifstream fileobj;
fileobj.open( filepath );
if( fileobj.fail() ) {
std::cerr << "ERROR: Failed to open the file '" << filepath << "'!" << std::endl;
}
try {
line.reserve( linecachesize );
}
catch( std::exception error ) {
std::cerr << "ERROR: Failed to alocate internal line buffer!" << std::endl;
}
bool getline() {
if( std::getline( fileobj, line ) ) {
// PyObject* pyobj = PyUnicode_DecodeUTF8( line.c_str(), line.size(), "replace" );
// linecache.push_back( pyobj );
// return true;
Py_XINCREF( emtpycacheobject );
linecache.push_back( emtpycacheobject );
return true;
}
return false;
}
if( fileobj.is_open() ) {
fileobj.close();
}
После удаления всех шаблонов из C ++ производительность для Posix C getline
была на 10% ниже встроенной в Python for line in file
:
const char* filepath = "./myfile.log";
size_t linecachesize = 131072;
PyObject* emtpycacheobject = PyUnicode_DecodeUTF8( "", 0, "replace" );
char* readline = (char*) malloc( linecachesize );
FILE* cfilestream = fopen( filepath, "r" );
static PyObject* PyFastFile_tp_call(PyFastFile* self, PyObject* args, PyObject *kwargs) {
Py_XINCREF( emtpycacheobject );
return emtpycacheobject;
}
static PyObject* PyFastFile_iternext(PyFastFile* self, PyObject* args) {
ssize_t charsread;
if( ( charsread = getline( &readline, &linecachesize, cfilestream ) ) == -1 ) {
return NULL;
}
Py_XINCREF( emtpycacheobject );
return emtpycacheobject;
}
static PyObject* PyFastFile_getlines(PyFastFile* self, PyObject* args) {
Py_XINCREF( emtpycacheobject );
return emtpycacheobject;
}
static PyObject* PyFastFile_resetlines(PyFastFile* self, PyObject* args) {
Py_INCREF( Py_None );
return Py_None;
}
static PyObject* PyFastFile_close(PyFastFile* self, PyObject* args) {
Py_INCREF( Py_None );
return Py_None;
}
Значения последнего запуска, в котором Posix C getline
уступал Python на 10%:
$ /bin/python3.6 fastfileperformance.py fastfile_time 1.15%, python_time 0.87%
Python timedifference 0:00:00.695292
FastFile timedifference 0:00:00.796305
$ /bin/python3.6 fastfileperformance.py fastfile_time 1.13%, python_time 0.88%
Python timedifference 0:00:00.708298
FastFile timedifference 0:00:00.803594
$ /bin/python3.6 fastfileperformance.py fastfile_time 1.14%, python_time 0.88%
Python timedifference 0:00:00.699614
FastFile timedifference 0:00:00.795259
$ /bin/python3.6 fastfileperformance.py fastfile_time 1.15%, python_time 0.87%
Python timedifference 0:00:00.699585
FastFile timedifference 0:00:00.802173
$ /bin/python3.6 fastfileperformance.py fastfile_time 1.15%, python_time 0.87%
Python timedifference 0:00:00.703085
FastFile timedifference 0:00:00.807528
$ /bin/python3.6 fastfileperformance.py fastfile_time 1.17%, python_time 0.85%
Python timedifference 0:00:00.677507
FastFile timedifference 0:00:00.794591
$ /bin/python3.6 fastfileperformance.py fastfile_time 1.20%, python_time 0.83%
Python timedifference 0:00:00.670492
FastFile timedifference 0:00:00.804689