本文參考:http://blog.csdn.net/taft/article/details/596291
如果你沒寫過php擴充,又是追求效能的極客,那麼這篇文章肯定適合你:
假如你有這樣一個php程式
function self_concat($string, $n){ $result = ""; for($i = 0; $i < $n; $i++){ $result .= $string; } return $result;}$str = self_concat('fire',10);
如果傳入的第二個參數N很大,程式的效能如何?我在自己的機器上測試下如果 n=10000000的時候耗時0.6s左右 如果用C寫這個php function然後php直接調用,會快嗎?那就開始寫這樣一個簡單的擴充吧,採用靜態編譯成.so的方式來載入,我用最快最簡明的方式說明。
1.首先你需要有php的源碼目錄 cd到其ext目錄下執行:
./ext_skel --extname=luckyext --proto=luckyext.def
這條命令會自動產生一個名叫luckyext的目錄 裡面有基本的擴充骨架檔案,核心的檔案只有三個 congif.m4用來做編譯配置,luckyext.h定義都檔案包括聲明你的自訂函數,還有luckyext.c用來寫C的函數源碼,其他都是附加的骨架檔案,暫時可以不用管。
2.在luckyext.c內編寫你要的函數,記得在標頭檔內聲明,不然編譯的時候會報錯
PHP_FUNCTION(self_concat_c) { char *str = NULL; int argc = ZEND_NUM_ARGS(); int str_len; long n; char *result; /* Points to resulting string */ char *ptr; /* Points at the next location we want to copy to */ int result_length; /* Length of resulting string */ if (zend_parse_parameters(argc TSRMLS_CC, "sl", &str, &str_len, &n) == FAILURE) return; /* Calculate length of result */ result_length = (str_len * n); /* Allocate memory for result */ result = (char *) emalloc(result_length + 1); /* Point at the beginning of the result */ ptr = result; while (n--) { /* Copy str to the result */ memcpy(ptr, str, str_len); /* Increment ptr to point at the next position we want to write to */ ptr += str_len; } /* Null terminate the result. Always null-terminate your strings even if they are binary strings */ *ptr = '\0'; /* Return result to the scripting engine without duplicating it*/ RETURN_STRINGL(result, result_length, 0); }
3.編譯擴充 關於php的環境配置就不說了
phpize./configuremake&&make install
成功編譯的話會在你的php指定的擴充目錄中產生一個luckyext.so的檔案
4.引入擴充重新載入php
vi /etc/php.iniextension=luckyext.so
我是mac機,修改的時候請看自己機器的配置,修改完後儲存重啟fpm
killall php-fpmphp-fpm
5.測試
終端輸入
php -m
出來的擴充中應該有luckyext了,至於它支援什麼函數 可以用ext/luckyext目錄內的luckyext.php指令碼去運行看看 正常情況會輸出它支援的函數self_concat_c()
6.效能對比 直接運行C寫的php
出來的結果耗時是驚人的,0.06秒,相差10倍!為什麼呢,因為如果用php那套代碼,每次往字串塞字元的時候,php都需要做一個記憶體的動態分配,迴圈越多次,效能開銷就越大,而C寫的function直接就計算出最終需要分配多少記憶體了,所以快就快在這裡,是不是很有趣~哈哈,至少我覺得很刺激! 本文的C例子屬參考前輩翻譯的檔案,以後要多修修C的功底才行了,後面我會研究更多C的知識,加油!