为什么用C ++编写的phpcpp扩展函数比用php编写的函数慢

时间:2017-08-09 18:22:03

标签: c++ php-extension php-cpp

我最近创建了一个带有PHPCPP - C++ library for developing PHP extensions的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 &params)
{
    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

结论用C ++编写的PHP函数慢4倍。 有人能说出原因吗?有没有办法用C ++改进我的代码?

0 个答案:

没有答案