日期:2014-05-17 浏览次数:20752 次
一直就知道PHP是C写的,网上大部分实际应用消耗性能的模块就是由PHP的拓展C来重写的,网上曾经看过百度的一篇大话PHP性能 ,对此文看法很是赞同的。
很早就相对PHP和C进行一个亲测的对比了,无奈当时对于Zend API不了解,现在本文就是亲自来测试一下C与PHP的差距。
我想不好拿什么来测试,于是题目就是对一个大小为3000的数组进行冒泡排序,看时间。
一共分为3种情况
1.C实现
#include <stdlib.h>
#include <stdio.h>
#include "time.h"
int main(int arg,char **argv)
{
clock_t start_time = clock();
int data[3000];
int i;
int length=sizeof(data)/sizeof(int);
for(i=0; i<length;i++)
{
data[i] = rand()%10000+1;
}
int j,temp;
for(i=0;i<length;i++)
{
for(j=0;j<length-1-i;j++)
{
if(data[j] > data[j+1])
{
temp = data[j];
data[j] = data[j+1];
data[j+1] = temp;
}
}
}
/* for(i=0;i<length;i++)
{
printf("%d\n",data[i]);
}*/
clock_t end_time = clock();
float time = (double)(end_time-start_time)/CLOCKS_PER_SEC;
printf("use time: %f",time);
return 0;
}
2.PHP
<?php
$start_time =microtime(true);
$data =array();
for($i=0; $i<3000; $i++)
{
array_push($data,rand(0,10000));
}
// var_dump($data);
$temp;
for($i=0;$i<count($data);$i++)
{
for($j=0;$j<count($data)-1-$i;$j++)
{
if($data[$j] > $data[$j+1])
{
$temp = $data[$j];
$data[$j] = $data[$j+1];
$data[$j+1] = $temp;
}
}
}
// var_dump($data);
$end_time =microtime(true);
$time = $end_time-$start_time;
echo "use time:" ,$time;
3.PHP的C拓展,由PHP产生数组,然后交给C处理数据
PHP_FUNCTION(bubble)
{
zval *array;
zval **item;
if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC,"a",&array)==FAILURE)
{
return;
}
int i;
int count;
count = zend_hash_num_elements(Z_ARRVAL_P(array));
int j,temp;
int data[count];
zend_hash_internal_pointer_reset(Z_ARRVAL_P(array));
for(i=0;i<count;i++