存档:php

博客记忆

四月 23, 2010 | c/c++, js/web, linux, mysql, php, 心情杂记, 数学 | RSS 2.0

很长时间没有更新日志,大概有几个月了,疏于对知识的学习和管理,可能是跟工作有点忙有关系吧,经常顾着不顾那个,放弃了诸多的学习机会,
不过希望以后能恢复,时间是一种财富,能让你积淀更多的对知识的理解,同时也能验证更多的真理,譬如坚持才是硬道理,这两个月坚持的最好的一件事情还算是对自己花销的记录很分类,方法比较土,就是使用网易的邮箱里的一个小插件,有时候别人问你一个月能花多少钱?像我这种不扫一屋的人是一无所知的,统计了下发现对多的是花在了吃上和没周末的超市。
记得以前写博客都是从外面copy一堆东西,可能是自己的知识欠缺的太多,发现一篇技术文章就copy过来,沾沾自喜一番感觉很有成就感,后来发现好多牛人都是自己写博客,发现自己土了,而且写的都是超高技术含量,,而且现在基本上很多的知识获取都是从blog获得的,自己也曾在google reader里面follow了一堆,曾经每天早上9点到公司都花费10分钟时间,不过有点不好,开始没分类好,造成后来好多看的时候乱,杂乱无章的,挑出那种令你很满意的需要去甄选,所以有时候就懒的去看了。
不过一些东西一旦写下来还是能整理下自己的思维的。而且能做下备忘,所以以后需要把这个习惯坚持下去。今天写这个主要是想试试用vim写博客,用的是vimpress插件,下载地址在http://www.vim.org/scripts/script.php?script_id=1953,下来后直接解压到.vim下就可以了,修改blog.vim下的秘密用户还xmlrpc就可以了。ok,here,travel start。

没有评论 »

debian上快速安装xcache

一月 5, 2010 | linux, php | RSS 2.0

不用phpize安装了,debian上可以迅速安装上,需要保证你的/etc/apt/sources.list下面是新的。

然后直接 apt-get install php5-xcache

/etc/init.d/apache2 restart

很快就看到结果了。可以用phpinfo看下。

php -r “phpinfo();”|grep “xcache”

/etc/php5/cli/conf.d/xcache.ini,
xcache.admin.enable_auth => On => On
xcache.cacher => On => On
xcache.coredump_directory => no value => no value
xcache.count => 1 => 1
xcache.coveragedump_directory => no value => no value
xcache.coverager => Off => Off
xcache.gc_interval => 0 => 0
xcache.mmap_path => /dev/zero => /dev/zero
xcache.optimizer => On => On
xcache.readonly_protection => no value => no value
xcache.shm_scheme => mmap => mmap
xcache.size => 0 => 0
xcache.slots => 8K => 8K
xcache.stat => On => On
xcache.test => no value => no value
xcache.ttl => 0 => 0
xcache.var_count => 1 => 1
xcache.var_gc_interval => 300 => 300
xcache.var_maxttl => 0 => 0
xcache.var_size => 0M => 0M
xcache.var_slots => 8K => 8K
xcache.var_ttl => 0 => 0

上面的就是配置相关信息,如果xcache_size=0就是关闭xcache的使用

具体配置参数的意义可以参考http://xcache.lighttpd.net/wiki/XcacheIni#XCacheCacher

然后可以做下压力测试,看看结果。

ab -c5 -n3000 http://liufb.kuxun.cn  并发连接为5,3000次请求

具体我用的是sudo ab -n 1000  http://liufb.kuxun.cn/beijing
安装xcache后的
Server Software:        Apache/2.2.9
Server Hostname:        liufb.kuxun.cn
Server Port:            80

Document Path:          /beijing
Document Length:        98026 bytes

Concurrency Level:      1
Time taken for tests:   373.665 seconds
Complete requests:      1000
Failed requests:        974
(Connect: 0, Receive: 0, Length: 974, Exceptions: 0)
Write errors:           0
Total transferred:      97639210 bytes
HTML transferred:       97172210 bytes
Requests per second:    2.68 [#/sec] (mean)
Time per request:       373.665 [ms] (mean)
Time per request:       373.665 [ms] (mean, across all concurrent requests)
Transfer rate:          255.18 [Kbytes/sec] received

Connection Times (ms)
min  mean[+/-sd] median   max
Connect:        0    0   0.0      0       0
Processing:   330  374 191.1    347    3689
Waiting:      139  188 190.8    162    3502
Total:        330  374 191.1    347    3689

Percentage of the requests served within a certain time (ms)
50%    347
66%    352
75%    355
80%    359
90%    374
95%    414
98%    753
99%   1298
100%   3689 (longest request)

Server Software:        Apache/2.2.9
Server Hostname:        liufb.kuxun.cn
Server Port:            80

Document Path:          /beijing
Document Length:        96315 bytes

Concurrency Level:      1
Time taken for tests:   401.374 seconds
Complete requests:      1000
Failed requests:        914
(Connect: 0, Receive: 0, Length: 914, Exceptions: 0)
Write errors:           0
Total transferred:      97633782 bytes
HTML transferred:       97166782 bytes
Requests per second:    2.49 [#/sec] (mean)
Time per request:       401.374 [ms] (mean)
Time per request:       401.374 [ms] (mean, across all concurrent requests)
Transfer rate:          237.55 [Kbytes/sec] received

Connection Times (ms)
min  mean[+/-sd] median   max
Connect:        0    0   0.0      0       0
Processing:   372  401  81.0    390    1504
Waiting:      185  213  80.5    202    1311
Total:        372  401  81.0    390    1504

Percentage of the requests served within a certain time (ms)
50%    390
66%    394
75%    398
80%    400
90%    413
95%    443
98%    561
99%    749
100%   1504 (longest request)

后用webbench测试结果可以看到:

没有安装xcache的测试。
liufb@kooxoo240:~/webbench/webbench-1.5$ webbench -c1000 -t 20 http://liufb.kuxun.cn/
Webbench – Simple Web Benchmark 1.5
Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.

Benchmarking: GET http://liufb.kuxun.cn/
1000 clients, running 20 sec.

Speed=903 pages/min, 318838 bytes/sec.
Requests: 301 susceed, 0 failed.

xcache的测试 xcache.size  =               32M

liufb@kooxoo240:~/webbench/webbench-1.5$ webbench -c1000 -t 20 http://liufb.kuxun.cn/
Webbench – Simple Web Benchmark 1.5
Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.

Benchmarking: GET http://liufb.kuxun.cn/
1000 clients, running 20 sec.

Speed=2388 pages/min, 430682 bytes/sec.
Requests: 796 susceed, 0 failed.

的安装不上可以看

http://www.howtoforge.com/xcache-php5-apache2-debian-etch

没有评论 »

批量替换文件夹下所有文件内容脚本(shell,php,python)

九月 14, 2009 | linux, php, python | RSS 2.0

批量替换一个文件夹下的字符或者其他的应该经常可以见到,近期读《卓有成效的程序员》有点感触,他提到了一些可以加快工作效率的容易让人忽略的小细节,加速法则,专注法则,自动化 法则,规范化法则。那这个批量替换应该属于自动化法则,有时候文件特别多的是很,替换是个非常容易烦人的事情。显然这些应该是计算机做的事情,下面给出以上三个版本:

shell:

sed跨行需要使用参数:N等控制,这里不适用,忘记。

shell学了个皮也不皮,毛也不毛

 
for i in `find . -name "*.html"`
do
sed "s|<\!--{if \!empty(\$this->_visiteduser->_gender)&& \(\$this->_visiteduser->_gender\)=='m'}-->他<\!--{else}--> 她<\!-  -{/if}-->|{\1}|g" $i > $i-new
mv $i $i-old
mv $i-new $i
done

当然你可以用sed的i直接替换,尽量替换前做个备份。

python的批量替换脚本:

刚开始学写的特别烂:

import os
import re
def getHtmlFile(rootdir):
allfile=[]
for   parent, dirnames, filenames   in   os.walk(rootdir):
for   filename   in   filenames:
#if os.path.isfile(os.path.join(0)
allfile.append(os.path.join(parent, filename))
return allfile
 
def replace(filename):
file_object = open(filename)
try:
all_the_text = file_object.read( )
finally:
file_object.close( )
'''
grouped_word = re.compile('<div id="header">([\s\S]*)?</div>')
all_the_text = re.sub(r'xxxxxxxxxxxxxxxxxx',all_the_text);
'''
all_the_text = re.sub('<div id="header">[\s\S]+?</div>','header',all_the_text);
all_the_text = re.sub('<div id="footer">[\s\S]+?</div>','footer',all_the_text);
#all_the_text = re.sub('\r','',all_the_text);
open(filename, 'w').write(all_the_text)
 
file=getHtmlFile('/home/liufb/studypython/gonglue');
test = re.compile("\.html$", re.IGNORECASE)
file = [f for f in file if test.search(f)]
for i in file:
print i+"\n"
replace(i)

学的时间相对比较长,但是依旧比较烂:

function changefile($filename) {
global $text1;
global $text2;
$file = file_get_contents($filename);
$file2 = preg_replace('@<div id="header">([\s\S]*)?</div>@iU',$text1,$file);
$file3 = preg_replace('@<div id="footer">([\s\S]*)?</div>@iU',$text2,$file2);
$file3 = preg_replace('@\r@iu','',$file3);
file_put_contents($filename,$file3);
 
}
function getFile($dirname) {
if ($handle = opendir($dirname)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$file=$dirname.'/'.$file;
if(is_file($file) && substr($file,-5) =='.html') {
//echo $file."\n";
 
changefile($file);
}else if(is_dir($dirname.'/'.$file)) {
$dirscan = realpath($file);
//$dirscan = $dirname.'/'.$file;
//echo $dirscan."\n";
getFile($dirscan);
}
}
}
}
closedir($handle);
}
getFile('.');

没有评论 »

安装php的调试工具xhprof

七月 5, 2009 | php | RSS 2.0

facebook出的一个php的调试工具:
相关文档在:http://mirror.facebook.net/facebook/xhprof/doc.html
http://pecl.php.net/package/xhprof
首先就是需要到http://pecl.php.net/package/xhprof下载,或者直接
wget http://pecl.php.net/package/xhprof
然后:
tar xzvf xhprof-0.9.2.tgz
cd xhprof-0.9.2
注意在安装前需要安装phpize如果没有安装
在ubuntu下可以apt-get install php5-dev
如果安装不上,则可以

ubuntu 安装:
apt-get install autoconf
apt-get install php5-dev

centos 安装:
yum install php-devel
yum install autoconf

安装完成后
root@liufabin-laptop:/opt/xhprof-0.9.2# cd extension/
root@liufabin-laptop:/opt/xhprof-0.9.2/extension# phpize
Configuring for:
PHP Api Version:         20041225
Zend Module Api No:      20060613
Zend Extension Api No:   220060519
下一步非常重要:
  ./configure –with-php-config=/usr/bin/php-config
checking for grep that handles long lines and -e… /bin/grep
checking for egrep… /bin/grep -E
checking for a sed that does not truncate output… /bin/sed
checking for gcc… gcc
checking for C compiler default output file name… a.out
checking whether the C compiler works… yes
checking whether we are cross compiling… no
checking for suffix of executables…
checking for suffix of object files… o
checking whether we are using the GNU C compiler… yes
checking whether gcc accepts -g… yes
checking for gcc option to accept ISO C89… none needed
checking whether gcc and cc understand -c and -o together… yes
checking for system library directory… lib
checking if compiler supports -R… no
checking if compiler supports -Wl,-rpath,… yes
checking build system type… i686-pc-linux-gnu
checking host system type… i686-pc-linux-gnu
checking target system type… i686-pc-linux-gnu
checking for PHP prefix… /usr
checking for PHP includes… -I/usr/include/php5 -I/usr/include/php5/main -I/usr/include/php5/TSRM -I/usr/include/php5/Zend -I/usr/include/php5/ext -I/usr/include/php5/ext/date/lib -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64
checking for PHP extension directory… /usr/lib/php5/20060613+lfs
checking for PHP installed headers prefix… /usr/include/php5
checking for re2c… no
configure: WARNING: You will need re2c 0.12.0 or later if you want to regenerate PHP parsers.
checking for gawk… no
checking for nawk… nawk
checking if nawk is broken… no
checking whether to enable xhprof support… yes, shared
checking for a sed that does not truncate output… (cached) /bin/sed
checking for fgrep… /bin/grep -F
checking for ld used by gcc… /usr/bin/ld
checking if the linker (/usr/bin/ld) is GNU ld… yes
checking for BSD- or MS-compatible name lister (nm)… /usr/bin/nm -B
checking the name lister (/usr/bin/nm -B) interface… BSD nm
checking whether ln -s works… yes
checking the maximum length of command line arguments… 1572864
checking whether the shell understands some XSI constructs… yes
checking whether the shell understands “+=”… yes
checking for /usr/bin/ld option to reload object files… -r
checking how to recognize dependent libraries… pass_all
checking for ar… ar
checking for strip… strip
checking for ranlib… ranlib
checking command to parse /usr/bin/nm -B output from gcc object… ok
checking how to run the C preprocessor… gcc -E
checking for ANSI C header files… yes
checking for sys/types.h… yes
checking for sys/stat.h… yes
checking for stdlib.h… yes
checking for string.h… yes
checking for memory.h… yes
checking for strings.h… yes
checking for inttypes.h… yes
checking for stdint.h… yes
checking for unistd.h… yes
checking for dlfcn.h… yes
checking for objdir… .libs
checking if gcc supports -fno-rtti -fno-exceptions… no
checking for gcc option to produce PIC… -fPIC -DPIC
checking if gcc PIC flag -fPIC -DPIC works… yes
checking if gcc static flag -static works… yes
checking if gcc supports -c -o file.o… yes
checking if gcc supports -c -o file.o… (cached) yes
checking whether the gcc linker (/usr/bin/ld) supports shared libraries… yes
checking whether -lc should be explicitly linked in… no
checking dynamic linker characteristics… GNU/Linux ld.so
checking how to hardcode library paths into programs… immediate
checking whether stripping libraries is possible… yes
checking if libtool supports shared libraries… yes
checking whether to build shared libraries… yes
checking whether to build static libraries… no
configure: creating ./config.status
config.status: creating config.h
config.status: config.h is unchanged
config.status: executing libtool commands
nfig
这个是默认的目录,你可以按照自己安装的目录更改
然后make&&make install 然后make test
即可,然后找到php.ini
添加:

1241 [xhprof]
1242 extension=xhprof.so
1243 ;#
1244 ;# directory used by default implementation of the iXHProfRuns
1245 ;# interface (namely, the XHProfRuns_Default class) for storing
1246 ;# XHProf runs.
1247 ;#
1248 xhprof.output_dir=/opt/xhprof/
 kilall -9 php
然后重启即可
你如果看到这个就算成功了
安装php的调试工具xhprof -  小和尚 - 小和尚真情无限
然后添加测试脚本:

<?php function bar($x) {  if ($x > 0) {    bar($x - 1);  }} function foo() {  for ($idx = 0; $idx < 2; $idx++) {    bar($idx);    $x = strlen("abc");  }} // start profilingxhprof_enable(); // run programfoo(); // stop profiler$xhprof_data = xhprof_disable(); // display raw xhprof data for the profiler runprint_r($xhprof_data);

结果为:Array(    [foo==>bar] => Array        (            [ct] => 2            [wt] => 15        )

    [foo==>strlen] => Array        (            [ct] => 2            [wt] => 0        )

    [bar==>bar@1] => Array        (            [ct] => 1            [wt] => 2        )

    [main()==>foo] => Array        (            [ct] => 1            [wt] => 38        )

    [main()==>xhprof_disable] => Array        (            [ct] => 1            [wt] => 0        )

    [main()] => Array        (            [ct] => 1            [wt] => 45        )

)

具体可以看文档

1条评论 »

统计php.err里的错误

六月 23, 2009 | mysql, php | RSS 2.0

如题:

awk -F “]” ‘{if(NF>=3){print $3} else{print $2}}’ php.err |sort|uniq|sed -e ’s/^:/ /’|awk ‘{print NR,$0}’ >only.err

删除掉script里的文本:

:%s#(<script contentType=”application/x-javascript”>)[^<]*(</script>)#12#

同事学习了下awk里的循环:
(摘抄)
awk条件语句

条件语句

awk中的条件语句是从C语言中借鉴过来的,可控制程序的流程。
14.5.1. if语句

格式:
{if (expression){
statement; statement; …
}
}

$ awk ‘{if ($1 <$2) print $2 “too high”}’ test。如果第一个域小于第二个域则打印。

$ awk ‘{if ($1 < $2) {count++; print “ok”}}’ test.如果第一个域小于第二个域,则count加一,并打印ok。
14.5.2. if/else语句,用于双重判断。

格式:
{if (expression){
statement; statement; …
}
else{
statement; statement; …
}
}

$ awk ‘{if ($1 > 100) print $1 “bad” ; else print “ok”}’ test。如果$1大于100则打印$1 bad,否则打印ok。

$ awk ‘{if ($1 > 100){ count++; print $1} else {count–; print $2}’ test。如果$1大于100,则count加一,并打印$1,否则count减一,并打印$1。
14.5.3. if/else else if语句,用于多重判断。

格式:
{if (expression){
statement; statement; …
}
else if (expression){
statement; statement; …
}
else if (expression){
statement; statement; …
}
else {
statement; statement; …
}
}

14.6. 循环

*

awk有三种循环:while循环;for循环;special for循环。
*

$ awk ‘{ i = 1; while ( i <= NF ) { print NF,$i; i++}}’ test。变量的初始值为1,若i小于可等于NF(记录中域的个数),则执行打印语句,且i增加1。直到i的值大于NF.
*

$ awk ‘{for (i = 1; i *

breadkcontinue语句。break用于在满足条件的情况下跳出循环;continue用于在满足条件的情况下忽略后面的语句,直接返回循环的顶端。如:

{for ( x=3; x<=NF; x++)
if ($x<0){print “Bottomed out!”; break}}
{for ( x=3; x<=NF; x++)
if ($x==0){print “Get next item”; continue}}

*

next语句从输入文件中读取一行,然后从头开始执行awk脚本。如:

{if ($1 ~/test/){next}
else {print}
}

*

exit语句用于结束awk程序,但不会略过END块。退出状态为0代表成功,非零值表示出错。

14.7. 数组

awk中的数组的下标可以是数字和字母,称为关联数组。
14.7.1. 下标与关联数组

*

用变量作为数组下标。如:$ awk {name[x++]=$2};END{for(i=0;i *

special for循环用于读取关联数组中的元素。格式如下:

{for (item in arrayname){
print arrayname[item]
}
}

$ awk ‘/^tom/{name[NR]=$1}; END{for(i in name){print name[i]}}’ test。打印有值的数组元素。打印的顺序是随机的。
*

用字符串作为下标。如:count["test"]
*

用域值作为数组的下标。一种新的for循环方式,for (index_value in array) statement。如:$ awk’{count[$1]++} END{for(name in count) print name,count[name]}’test。该语句将打印$1中字符串出现的次数。它首先以第一个域作数组count的下标,第一个域变化,索引就变化。
*

delete函数用于删除数组元素。如:$ awk ‘{line[x++]=$1} END{for(x in line) delete(line[x])}’test。分配给数组line的是第一个域的值,所有记录处理完成后,special for循环将删除每一个元素。

没有评论 »

如何优化你的php(二)

五月 26, 2009 | php | RSS 2.0

–> –>

翻译:http://phplens.com/lens/php-book/optimizing-debugging-php.php

今天翻译着翻译着,已经烦了,看来真的持之以恒做一件事很难,尤其是不太喜欢的事情,我略过和跳过,和翻译错了很多。

php调试你的web服务器

我们将论述在今天两种非常常用的web服务器如何得到最好的性能,apache1.2iis,当然也有许多关于服务html的建议。

Php的作者表示apache2.0相对于apache1.3没有性能和架构的优点,特别是多线程模式,但apache2.0以预分配模式运行的时候,下面的讨论依然有关系(200311 21

aapache1.3/2.0

apache可以运行在unixwindows上面,它是当今世界最流行的服务器,apache1.3在服务器运行时用了预分配模式,但它启动时,它会创建多个子进程来处理http请求,初始化的父进程间就像一个呵护天使,确保每个子进程工作地顺利同时协调所有的事情,越多的http请求过来,越多的子进程出来处理它们,但http请求慢下来的时候,父进程会杀死一个空闲的进程,为别的进程释放资源,这个模式使得apache非常的健壮,即使一个子进程崩溃了,父进程和别的进程是和这个崩溃的进程独立的。

预分配模式不像别的设计的那么快,但对我来说,服务一个php脚本足够了,当apache性能组织非常重大的影响前还有很多别的瓶颈要找。Apache的健壮性和信赖性非常重要。

Apace2.0提供了在执行时采用多线程模式,我的测试表明在这种模式下只有一点性能上的优点。当然好多php的扩展部兼容。Apache2.0.472003)。

Apache的配置使用httpd.conf,下面的参数在配置子进程的时候非常重要。

命令

默认

描述

MaxClients

256

最大的子进程的数量,默认的意思是最多同时处理256http请求,多的连接被放在队列里。

StartServers

5

启动时候创建的子进程个数

MinSpareServers

5

需要创建的空闲子进程的数目,如果子进程的数目低于这个数字,1个子进程被初始化创建,然后是2个,后来是4个,直到32个被创建每秒钟

MaxSpareServers

10

如果激活的子进程多于这个数字,多的进程将被中止掉

MaxRequestsPerChild

0

子进程中止前能处理的http请求数.设置成0 表示永远不终止.设置为10010000如果你怀疑有内存泄漏,或者来释放一些没有用的资源.

如果是大一点的网站,值设置成下面的会好一点:

MinSpareServers32

MaxSpareServers64

Apachewindows有点不一样,它不是用子进程,而是用线程,上面的参数将不会用到,相比我们有一个参数:ThreadsPerChild,默认的是50,这个参数表示apache可以多少个线程交换.windows的版主中只有一个子进程,默认的设置成50 当前只可以处理50个请求。但web服务器经历高的网络流量时,增加它在2561024之间,一些有用的参数你可以改变,包括如下:

参数

默认

描述

SendBufferSize

设置成操作系统默认的

决定在用tcp/ip连接时候用到的输出的缓冲大小。对于忙的网络是非常有用的当你缓存时候,你可以设置这个参数关闭最大的文件下载。每个客户端连接的时候tcp/ip缓冲都会创建。

KeepAlive [on|off]

On

在老的http协议中,每个http请求都需要在服务器上单独建立个连接。为了减少过多的正常连接,keep-live的头被发展开了,它告诉服务器继续使用同一个socket处理多个请求,如果一个独立的专为突破服务器的服务器,你可以关闭这个选项,这个技术很大的提高了资源的可用性.

KeepAliveTimeout

15

这个数字式保持socket连接的存活时间,这个时间包括服务器生成内容,和客户机响应,如果客户机不响应,他将生成一个新连接。这个值得将保持低值做为

没有评论 »

如何优化php(-)

五月 26, 2009 | php | RSS 2.0

翻译:http://phplens.com/lens/php-book/optimizing-debugging-php.php

Php是一门快速的web编程开发语言,远比php代码的执行的速度还有更多需要我们的优化,

这作者的文章中将给你介绍优化你的php有许多和编码不相关的多个因素,调试我们的php需要我们理解更多的和php运行相关的东西,如服务器,找出问题的瓶颈,修复他们,这里将讲述如何调试优化他们,使他们执行的更快。

       获得更好的性能

       当我们将好的性能的时候,我们不止是讲你的脚步运行的有多快,性能是你的架构和速度之间的平衡,脚步可能用少的资源可能比缓存的执行要慢,但是多个复制的同一个脚步在一个服务器上可以同时执行。

       在下面的例子中,A.php是一个短跑的能跑的很快,但是B.php则是一个马拉松选手在一个很长的时间内跑同样的速度,负载比较轻的情况下,A.php相继会很快,但是网络流量增加时,当A.php跑完了气力的时候B.php只是降低了一点。

如何优化php(-) - 玉树临风 - 小和尚真情无限

让我们举更现实的例子来阐述的更透彻,假设我们需要写一个php的脚本,来读取一个250k的文件来生成一个html的大致内容,写两个php来做同样一个事情,hare.php读取一次整个文件到内存,一次性处理文件,tortoise.php读文件,一次读取一行使内存中不保留更多的内容,tortoise.php但多次读取的时候会变慢,需要更多的系统的调用,hare.php需要0.04秒和10mramtoroise.php需要0.06秒和5mram,服务器有100m的空内存,这时cpu99%的空闲,简单的假设没有内存碎片。

    10次脚本,hare.php会内存泄漏,在这个时候toroise还有50m的空闲内存,当低11次的时候,hare.php不得不去请开始虚拟内存交换,这使得他的速度将会减少为原来的一般,每次hare.php的执行,将花费cpu0.08秒,同时,toroise.php将会继续保持原来的0.06秒,在下表中,在不同的负载下快的php将会用粗体标出:

 

 

 

 

 

      

连接

1http请求cpu需要的时间

10http请求cpu需要的时间

11http请求cpu需要的时间

hare.php

0.04

0.40

0.88
(runs out of RAM)

tortoise.php

0.06

0.60

0.66

从上面的例子我们将看出,获得好的性能,不仅关系到写好的php脚本,高性能的php需要理解硬件,操作系统,以及他支持的软件,如服务器,数据库。

瓶颈

       上面的sharetororse的例子说明了瓶颈导致慢了下来,有无限多的ram的时候hare.php将会永远的比tortoize.php快,不幸的是,上面的例子有点简单,除了ram还有许多瓶颈影响。

(a)   网络

你的网络将是最大的瓶颈,假设你有10m的连接到因特网上,你能在一秒钟输出1m字节的数据,如果一个页面是30k,只需要一秒钟33个页面就使得你饱和,许多微妙的网络瓶颈包括正常的请求到慢的服务如,dns,分配不够多的内存给网络软件,

(b) cpu

如果你监视你的cpu负载,通过网络发送一个html页面,不单单要耗费你的cpu,就像我们提到的瓶颈是网络,但是php生成的复杂的动态页面,你的cpu的速度将会变成有限度的因素,多核处理器或者服务器集群能做到。

(c) 共享内存

共享内存是用在进程内的交换,在多进程中存储资源,比如缓存数据和代码,如果内存分配的不足,任何连接这些用于内存共享,如数据库连接,代码执行等资源都会有很差的性能。

(d) 文件系统

    从硬盘中读取数据要比ram中慢50100倍,文件缓存用ram能完成这些,尽管低内存的状态讲减少文件缓存中内存利用的次数,文件系统当然也会带来系统碎片,降低硬盘的读取,过多的使用符号链接在unix系统中将减慢硬盘的读取。

e)进程管理

在一些操作系统中,比如windows中创建一个新进程将是一个很慢的操作,这就意味这cgi程序需要创建一个新进程在每一个激活的连接中,在这些操作系统中这将非常的慢,在多线程下跑php可能提高反应的时间。(注:老版本的php在多线程下不稳定)。

在你的服务器中避免过多的不需要的进程,比如,如果你的服务器只做web服务器,避免跑甚至装x-winows在机器上,在windows上,避免跑微软的查找部分,和三维的屏保会导致cpu100%.

一些程序包括你考虑移除掉没有用的网络协议,邮件服务器,杀毒扫描,硬件鼠标驱动,红外线端口,等,在unix下,加入你连接你的服务器你用ssh,你可以考虑卸载掉一下:一些守护进程如: telnetd, inetd, atd, ftpd, lpd, sambad,发送邮件的接受mailportmap for NFS
xfs, fvwm, xinit, X

你可以禁用一些各种各样的服务通过修改启动文件,这些文件通常保存在/etc/init* 或者/etc/rc*/init*文件下下。

同时查看下你的crontab文件,你是否需要移除他们,或者重新规划。

f)连接其他服务器

如 …

没有评论 »

解决location.href在ie下得不到referer

五月 19, 2009 | php | RSS 2.0

/**
*功能:解决onclick.href 跳转时候在ie下得不到refer的问题
*@url 需要跳转的地方
*@author fabin
*使用方法:onclick=”href(’url’)”
*/
function href(url){
    var fakeLink = document.createElement (”a”);
    if (typeof(fakeLink.click) == ‘undefined’)
        location.href = url;  // sends referrer in FF, not in IE
    else
    {
        fakeLink.href = url;
        document.body.appendChild(fakeLink);
        fakeLink.click();   // click() method defined in IE only
    }

}
另外一种方式

function goTo(url) {
    var a = document.createElement(”a”);
    if(!a.click) { //only IE has this (at the moment);
        window.location = url;
        return;
    }
    a.setAttribute(”href”, url);
    a.style.display = “none”;
    document.bodyappendChild(a);
    a.click();
}

没有评论 »

如何让自己写的服务器支持php?

五月 15, 2009 | c/c++, php | RSS 2.0

 写一个支持支持静态的文件的c服务器很简单,就是些文件目录等操作,如何写一个支持get方式php的呢?
很简单的可以用一个shell搞定 ,例如,但是如何支持post等操作呢?
#include <stdio.h>
void command_mess(char *command, char *buf, int length)
{
    FILE   *stream;

    stream = popen(command,”r”);
    fread( buf, sizeof(char), length,  stream);
    pclose( stream );
    return;
}

int main( void )
{
    char buf[4096] = “”;  //请注意系统命令要输出的数据大小,小心得到的数据不全哦
    char com[64] = “/home/liufabin/php/bin/php test.php”;
    command_mess(com, buf, sizeof(buf));
    printf(”Message:%s”,buf);
    return 0;

}

没有评论 »

启动

三月 10, 2009 | linux, mysql, php | RSS 2.0

启动 mysql
sudo /etc/init.d/mysql restart

 1)启动fast_cgi:

  spawn-fcgi -a 127.0.0.1 -p 9000 -C 5 -u www-data -g www-data -f /usr/bin/php-cgi

  注意:ip,端口与nginx服务器中的cgi-pass要对应. -C表示打开几个cgi进程

  2)启动nginx  (配置为上面server的设置)

   sudo /etc/init.d/nginx start

#! /bin/sh

### BEGIN INIT INFO
# Provides:          nginx
# Required-Start:    $all
# Required-Stop:     $all
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: starts the nginx web server
# Description:       starts nginx using start-stop-daemon
### END INIT INFO

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/nginx
NAME=nginx
DESC=nginx

test -x $DAEMON || exit 0

# Include nginx defaults if available
if [ -f /etc/default/nginx ] ; then
    . /etc/default/nginx
fi

set -e

. /lib/lsb/init-functions

case “$1″ in
  start)
    echo -n “Starting $DESC: “
    start-stop-daemon –start –quiet –pidfile /var/run/$NAME.pid
        –exec $DAEMON — $DAEMON_OPTS || true
    echo “$NAME.”
    ;;
  stop)
    echo -n “Stopping $DESC: “
    start-stop-daemon –stop –quiet –pidfile /var/run/$NAME.pid
        –exec $DAEMON || true
    echo “$NAME.”
    ;;
  restart|force-reload)
    echo -n “Restarting $DESC: “
    start-stop-daemon –stop –quiet –pidfile
        /var/run/$NAME.pid –exec $DAEMON || true
    sleep 1
    start-stop-daemon –start –quiet –pidfile
        /var/run/$NAME.pid –exec $DAEMON — $DAEMON_OPTS || true
    echo “$NAME.”
    ;;
  reload)
      echo -n “Reloading $DESC configuration: “
      start-stop-daemon –stop –signal HUP –quiet –pidfile /var/run/$NAME.pid
          –exec $DAEMON || true
      echo “$NAME.”
      ;;
  status)
      status_of_proc -p /var/run/$NAME.pid “$DAEMON” nginx && exit 0 || exit $?
      ;;
  *)
    N=/etc/init.d/$NAME
    echo “Usage: $N {start|stop|restart|reload|force-reload|status}” >&2
    exit 1
    ;;
esac

exit 0

没有评论 »