Почему функция расширения phpcpp, написанная на C++, работает медленнее, чем функция, написанная на php
Недавно я создал расширение php с библиотекой PHPCPP - C++ для разработки расширений PHP и ожидал повышения производительности, однако вместо того, чтобы видеть повышение, я вижу только снижение производительности. Я считаю, что я делаю что-то неправильно, и, возможно, кто-то может заметить, почему это происходит?
Вот код C++:
#include <phpcpp.h>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <string>
#include <regex>
#include <stdlib.h> /* atof,strtod */
#include <cstddef> // std::size_t
#include <sstream>
#include <vector>
#include <boost/algorithm/string.hpp> // include Boost, a C++ library
#include <boost/regex.hpp>
using namespace std;
Php::Value test_function(Php::Parameters ¶ms)
{
double a = params[0];
double b = params[1];
return (a + b) * (a - b) / 100;
}
/**
* Switch to C context, because the Zend engine expects get get_module()
* to have a C style function signature
*/
extern "C" {
/**
* Startup function that is automatically called by the Zend engine
* when PHP starts, and that should return the extension details
* @return void*
*/
PHPCPP_EXPORT void *get_module()
{
// the extension object
static Php::Extension extension("test_extension", "1.0");
// add functions so that they can be called from PHP scripts
extension.add("test_function", test_function, {
Php::ByVal("a", Php::Type::Float,true),
Php::ByVal("b", Php::Type::Float,true)
});
// return the extension details
return extension;
}
}
Вот компиляция расширения командной строки:
[root@test test_extension]# make
g++ -Wall -c -O2 -std=c++11 -fpic -o main.o main.cpp
g++ -shared -o test_extension.so main.o -lphpcpp
[root@test test_extension]# make install
cp -f test_extension.so /usr/lib64/php/modules
cp -f test_extension.ini /etc/php.d
Вот мой простой тест:
<?php
//function written in php
function local_test_function($a,$b){
$res = ($a + $b) * ($a - $b) / 100;
return $res;
}
$output = '';
//local php function test
$start_time = microtime(true);
$output.= "<br> test_function local: " . local_test_function(123.4,12.5);
$end_time = microtime(true);
$duration = $end_time - $start_time;
$duration = number_format($duration,20);
$output.=", Duration: ".$duration.'<br>';
// function written in c++
$start_time = microtime(true);
$output.= "function written in c++: " . test_function(123.4,12.5);
$end_time = microtime(true);
$duration = $end_time - $start_time;
$duration = number_format($duration,20);
$output.=", Duration: ".$duration . '<br>';
?>
Результаты:
test_function local result: 150.7131, Duration: 0.00000715255737304688
function written in c++ result: 150.7131, Duration: 0.00003004074096679688
PHP-функция вывода, написанная на C++, в 4 раза медленнее. Может кто-нибудь сказать, почему? И есть ли способ улучшить мой код на C++?
1 ответ
ОБНОВЛЕНИЕ и ОТВЕТ
как и предполагалось, я пытаюсь протестировать более сложную функцию, чтобы увидеть, вызывает ли перегрузка медленную функцию C++
я изменил существующую функцию "test_function" + добавил другую функцию "test_function_inner" и объявил ее.
double test_function_inner(double a, double b);
Php::Value test_function(Php::Parameters ¶ms)
{
double a = params[0];
double b = params[1];
double res = 0.0;
int i = 100;
while (i > 0) {
res = res + test_function_inner(a, b);
--i;
}
return res;
}
double test_function_inner(double a, double b) {
double res = 0.0;
while (b > a) {
res = res + (a + b) * (a - b) / 100;
b = b - 1;
}
return res;
}
Тестирование:
<?php
$output = '';
//local php function test
$start_time = microtime(true);
$output.= "<br> test_function local: " . local_test_function(123.4,1200000.5);
$end_time = microtime(true);
$duration = $end_time - $start_time;
$duration = number_format($duration,20);
$output.=", Duration: ".$duration.'<br>';
// function written in c++
$start_time = microtime(true);
$output.= "function written in c++: " . test_function(123.4,1200000.5);
$end_time = microtime(true);
$duration = $end_time - $start_time;
$duration = number_format($duration,20);
$output.=", Duration: ".$duration . '<br>';
?>
результаты:
test_function local result: -5.7600142172989E+17, Duration: 9.23940896987915039062
function written in c++ result: -5.7600142172989E+17, Duration: 0.72759604454040527344
ЗАКЛЮЧЕНИЕ это было связано с накладными расходами, вызванными начальным вызовом функции, как было предложено, и небольшие операции и вычисления не стоят того, чтобы помещать их в отдельные функции в расширении, так как это не улучшило бы приложение, а вместо этого отрицательно сказалось бы на производительности.