Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Saturday 22 April 2017

Benchmark memcached vs memcache vs redis

My setup:
Fedora 25,Nginx 1.10.2,redis 3.1.2,memcache 3.0.9,memcached 3.0.3,php-fpm 7.0.17.

My Benchmark script(php)
<?php
################# memcached ###################################################
    
    $k=0;
    $t_time=0;
    echo "
Benchmark memcached :
"; $memcached = new Memcached; $memcached->addServer("127.0.0.1", 11211)or die ("Cannot connect"); $original_string = 'abcdefghijklmnopqrstuvwxyz'; for ($i=0;$i<=10000;$i++){ $random_string = get_random_string($original_string, 10); $random_string2 = get_random_string($original_string, 10); $a1[$i]=$random_string; $a2[$random_string]=$random_string2; } $tstart=timer_start(); for ($i=0;$i<=10000;$i++){ $memcached->set($a1[$i], $a2[$a1[$i]],20) or die ("Cannot save data"); } $t_time=timer_end($tstart); echo "Total Set time: ".$t_time."
"; for ($j=0;$j<10;$j++){ $tstart=timer_start(); for ($i=0;$i<=10000;$i++){ $value = $memcached->get($a1[$i]); } $t_time=timer_end($tstart); echo "Loop $j (Get) time: ".$t_time."
"; $k=$k+$t_time; } echo "Total 10 loop Get time $k
"; ################# memcache ################################################### $k=0; $t_time=0; echo "
Benchmark memcache :
"; $memcache = new Memcache; $memcache->connect('127.0.0.1', 11211) or die ("Cannot connect"); $original_string = 'abcdefghijklmnopqrstuvwxyz'; for ($i=0;$i<=10000;$i++){ $random_string = get_random_string($original_string, 10); $random_string2 = get_random_string($original_string, 10); $a1[$i]=$random_string; $a2[$random_string]=$random_string2; } $tstart=timer_start(); for ($i=0;$i<=10000;$i++){ $memcache->set($a1[$i], $a2[$a1[$i]], false, 20) or die ("Cannot save data"); } $t_time=timer_end($tstart); echo "Total Set time: ".$t_time."
"; for ($j=0;$j<10;$j++){ $tstart=timer_start(); for ($i=0;$i<=10000;$i++){ $value = $memcache->get($a1[$i]); } $t_time=timer_end($tstart); echo "Loop $j (Get) time: ".$t_time."
"; $k=$k+$t_time; } echo "Total 10 loop Get time $k
"; ################# redis ################################################### $k=0; $t_time=0; echo "
Benchmark redis :
"; $redis = new Redis(); $redis->connect('127.0.0.1', 6379); $original_string = 'abcdefghijklmnopqrstuvwxyz'; for ($i=0;$i<=10000;$i++){ $random_string = get_random_string($original_string, 10); $random_string2 = get_random_string($original_string, 10); $a1[$i]=$random_string; $a2[$random_string]=$random_string2; } $tstart=timer_start(); for ($i=0;$i<=10000;$i++){ $redis -> set($a1[$i],$a2[$a1[$i]]); } $t_time=timer_end($tstart); echo "Total Set time: ".$t_time."
"; for ($j=0;$j<10;$j++){ $tstart=timer_start(); for ($i=0;$i<=10000;$i++){ $value=$redis -> get($a1[$i]); } $t_time=timer_end($tstart); echo "Loop $j (Get) time: ".$t_time."
"; $k=$k+$t_time; } echo "Total 10 loop Get time $k
"; function timer_start() { $time = microtime(); $time = explode(" ", $time); $time = $time[1] + $time[0]; return $time; } function timer_end($start) { $time = microtime(); $time = explode(" ", $time); $time = $time[1] + $time[0]; return $time-$start; } function get_random_string($valid_chars, $length) { // start with an empty random string $random_string = ""; // count the number of chars in the valid chars string so we know how many choices we have $num_valid_chars = strlen($valid_chars); // repeat the steps until we've created a string of the right length for ($i = 0; $i < $length; $i++) { // pick a random number from 1 up to the number of valid chars $random_pick = mt_rand(1, $num_valid_chars); // take the random character out of the string of valid chars // subtract 1 from $random_pick because strings are indexed starting at 0, and we started picking at 1 $random_char = $valid_chars[$random_pick-1]; // add the randomly-chosen char onto the end of our string so far $random_string .= $random_char; } // return our finished random string return $random_string; } ?>
Benchmark memcached : 
Total Set time: 0.69209885597229
Loop 0 (Get) time: 0.68401622772217
Loop 1 (Get) time: 0.67029213905334
Loop 2 (Get) time: 0.77216291427612
Loop 3 (Get) time: 0.68823003768921
Loop 4 (Get) time: 0.68713402748108
Loop 5 (Get) time: 0.66251420974731
Loop 6 (Get) time: 0.66882991790771
Loop 7 (Get) time: 0.63542795181274
Loop 8 (Get) time: 0.66616487503052
Loop 9 (Get) time: 0.66425609588623
Total 10 loop Get time 6.7990283966064 

Benchmark memcache : 
Total Set time: 0.72946310043335
Loop 0 (Get) time: 0.55730509757996
Loop 1 (Get) time: 0.46489191055298
Loop 2 (Get) time: 0.68988108634949
Loop 3 (Get) time: 0.73450708389282
Loop 4 (Get) time: 0.68325591087341
Loop 5 (Get) time: 0.67392992973328
Loop 6 (Get) time: 0.7195930480957
Loop 7 (Get) time: 0.74770784378052
Loop 8 (Get) time: 0.70041298866272
Loop 9 (Get) time: 0.70169019699097
Total 10 loop Get time 6.6731750965118 

Benchmark redis : 
Total Set time: 0.69859886169434
Loop 0 (Get) time: 0.69667816162109
Loop 1 (Get) time: 0.65093517303467
Loop 2 (Get) time: 0.68474006652832
Loop 3 (Get) time: 0.7402458190918
Loop 4 (Get) time: 0.6503758430481
Loop 5 (Get) time: 0.66205310821533
Loop 6 (Get) time: 0.70370101928711
Loop 7 (Get) time: 0.646409034729
Loop 8 (Get) time: 0.66896295547485
Loop 9 (Get) time: 0.67996406555176
Total 10 loop Get time 6.784065246582 
The results shows for simple Set and Get,memcached is quite comparable to redis.
And the result is not repeatable. Different results occurrs at different run.

For other functions,more extensive tests/benchmarks have to perform on both.

Friday 27 February 2015

Install MongoDB with PHP on Fedora

MongoDB is an open-source database used by companies of all sizes, across all industries and for a wide variety of applications. It is an agile database that allows schemas to change quickly as applications evolve, while still providing the functionality developers expect from traditional databases, such as secondary indexes, a full query language and strict consistency.

This tutorial looks into how to install latest MongoDB with PHP on Fedora.

Create a /etc/yum.repos.d/mongodb.repo file:
vi /etc/yum.repos.d/mongodb.repo
If you are running a 64-bit system, use the following configuration:
[mongodb]
name=MongoDB Repository
baseurl=http://downloads-distro.mongodb.org/repo/redhat/os/x86_64/
gpgcheck=0
enabled=1
else for 32-bit system, use:
[mongodb]
name=MongoDB Repository
baseurl=http://downloads-distro.mongodb.org/repo/redhat/os/i686/
gpgcheck=0
enabled=1
To install the latest stable version of MongoDB, issue the following command:
yum install -y mongodb-org
Install php,mongo driver:
pecl install mongo
create a mongo (php) ini
vi /etc/php.d/mongo.ini
And include the driver:
extension=mongo.so
Enable mongod on startup
systemctl enable mongod
start mongod:
service mongod start
Open mongo client to test.
mongo
create database test:
use test
Lets do an insert:
db.collection1.insert({"name":"desc"})
And lets do an query:
db.collection1.find();
Lets proceed with using mongodb in php. Restart php-fpm:
systemctl restart php-fpm.service
We shell create a php script:
<?php
$connection = new Mongo();
$dbname = $connection->selectDB('test');
$collection = $dbname->collection1;
$arr = array(
        'name' => 'MongoDB',
        'desc' => 'MongoDB is a document database.'
);
$collection->insert($arr);
$result = $collection->find();
foreach ($result as $document) {
        echo $document["name"]."\n";
        echo $document["desc"]."\n";
}
?>
You can run above script in web server or just run:
php test_mongo.php

Tuesday 17 February 2015

Benchmark redis 2.8.19 with memcache 1.4.22

Having read a few articles on comparing redis with memcache. I decided to benchmark myself.

My setup:
Fedora 21,Nginx 1.6.2,redis 2.8.19,memcache 1.4.22,php-fpm 5.6.4.

My Benchmark script(php)
<?php
    ################# redis ###################################################
    $k=0;
    $t_time=0;
    echo "Benchmark redis : 
"; $redis = new Redis(); $redis->connect('127.0.0.1', 6379); $original_string = 'abcdefghijklmnopqrstuvwxyz'; for ($i=0;$i<=10000;$i++){ $random_string = get_random_string($original_string, 10); $random_string2 = get_random_string($original_string, 10); $a1[$i]=$random_string; $a2[$random_string]=$random_string2; } $tstart=timer_start(); for ($i=0;$i<=10000;$i++){ $redis -> set($a1[$i],$a2[$a1[$i]]); } $t_time=timer_end($tstart); echo "Total Set time: ".$t_time."
"; for ($j=0;$j<10;$j++){ $tstart=timer_start(); for ($i=0;$i<=10000;$i++){ $value=$redis -> get($a1[$i]); } $t_time=timer_end($tstart); echo "Loop $j (Get) time: ".$t_time."
"; $k=$k+$t_time; } echo "Total 10 loop Get time $k
"; ################# memcache ################################################### $k=0; $t_time=0; echo "
Benchmark memcache :
"; $memcache = new Memcache; $memcache->connect('127.0.0.1', 11211) or die ("Cannot connect"); $original_string = 'abcdefghijklmnopqrstuvwxyz'; for ($i=0;$i<=10000;$i++){ $random_string = get_random_string($original_string, 10); $random_string2 = get_random_string($original_string, 10); $a1[$i]=$random_string; $a2[$random_string]=$random_string2; } $tstart=timer_start(); for ($i=0;$i<=10000;$i++){ $memcache->set($a1[$i], $a2[$a1[$i]], false, 20) or die ("Cannot save data"); } $t_time=timer_end($tstart); echo "Total Set time: ".$t_time."
"; for ($j=0;$j<10;$j++){ $tstart=timer_start(); for ($i=0;$i<=10000;$i++){ $value = $memcache->get($a1[$i]); } $t_time=timer_end($tstart); echo "Loop $j (Get) time: ".$t_time."
"; $k=$k+$t_time; } echo "Total 10 loop Get time $k
"; function timer_start() { $time = microtime(); $time = explode(" ", $time); $time = $time[1] + $time[0]; return $time; } function timer_end($start) { $time = microtime(); $time = explode(" ", $time); $time = $time[1] + $time[0]; return $time-$start; } function get_random_string($valid_chars, $length) { $random_string = ""; $num_valid_chars = strlen($valid_chars); for ($i = 0; $i < $length; $i++) { $random_pick = mt_rand(1, $num_valid_chars); $random_char = $valid_chars[$random_pick-1]; $random_string .= $random_char; } return $random_string; } ?>
Benchmark redis : 
Total Set time: 0.12764096260071
Loop 0 (Get) time: 0.175616979599
Loop 1 (Get) time: 0.18264698982239
Loop 2 (Get) time: 0.13450312614441
Loop 3 (Get) time: 0.1352870464325
Loop 4 (Get) time: 0.13448214530945
Loop 5 (Get) time: 0.13312005996704
Loop 6 (Get) time: 0.15526604652405
Loop 7 (Get) time: 0.40630602836609
Loop 8 (Get) time: 0.13408994674683
Loop 9 (Get) time: 0.13564801216125
Total 10 loop Get time 1.726966381073 

Benchmark memcache : 
Total Set time: 0.14455795288086
Loop 0 (Get) time: 0.12623596191406
Loop 1 (Get) time: 0.13038897514343
Loop 2 (Get) time: 0.1564610004425
Loop 3 (Get) time: 0.11394095420837
Loop 4 (Get) time: 0.11402487754822
Loop 5 (Get) time: 0.11300802230835
Loop 6 (Get) time: 0.11119389533997
Loop 7 (Get) time: 0.1115710735321
Loop 8 (Get) time: 0.11155104637146
Loop 9 (Get) time: 0.19941091537476
Total 10 loop Get time 1.28778672218322
The results shows for simple Set and Get, redis is faster. For SET, redis is faster by 12% For GET, memcache is faster by 25%

For other functions,more extensive tests/benchmarks have to perform on both.

Thursday 29 January 2015

Install Nginx (and PHP) server on Fedora

Nginx [engine x] is a free high-perfomance HTTP and reverse proxy server, as well as a mail proxy server, written by Igor Sysoev.

Lets start the installation process:
Stop and disable existing apache.

# systemctl stop httpd.service
# systemctl disable httpd.service 

Install php-fpm

# yum install php-fpm -y

Enable and start php-fpm service:

# systemctl enable php-fpm.service
# systemctl start php-fpm.service

To install Nginx

# yum install nginx -y

Enable and start Nginx service

# systemctl enable nginx.service
# systemctl start nginx.service

Test Nginx

Open up your web browser and navigate to http://localhost/ (example). You will see the default nginx welcome screen.

Configure Nginx

Open the file /etc/nginx/nginx.conf in vi

# vi /etc/nginx/nginx.conf

Set the worker_processes (No. Of CPU’s in your system you want to utilise). To see the no. Of CPU’s, you can use the command “lscpu”. For default you can set to 1.
worker_processes 1;

Example of working nginx.conf:

# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log;
#error_log  /var/log/nginx/error.log  notice;
#error_log  /var/log/nginx/error.log  info;

pid        /run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    index   index.html index.htm;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    #Change below value to suit your need:
    fastcgi_read_timeout 6000s;

    server {
        listen       80 default_server;
        server_name  localhost;
        root         /usr/share/nginx/html;

        #charset koi8-r;

        #access_log  /var/log/nginx/host.access.log  main;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
        }

        # redirect server error pages to the static page /40x.html
        #
        error_page  404              /404.html;
        location = /40x.html {
        }

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
        }

        location ~ [^/]\.php(/|$) {
           fastcgi_split_path_info ^(.+?\.php)(/.*)$;
           if (!-f $document_root$fastcgi_script_name) {
              return 404;
           }

           fastcgi_pass 127.0.0.1:9000;
           fastcgi_index index.php;
           include fastcgi_params;           
        }
    }
}

Save and close the file. Restart Nginx service:

# systemctl restart nginx.service

Test PHP

Create a sample “phpinfo.php” file in the nginx document root folder:

# vi /usr/share/nginx/html/phpinfo.php

Append the lines as shown below:



Save and close the file. Restart Nginx service:

# systemctl restart nginx.service

Navigate to http://localhost/testphp.php (example). It will display all the details about PHP,build,setups.

Friday 9 January 2015

httpd: segmentation fault (GDB)

During one of my php programming, I encountered a httpd segmentation fault. The error was shown in error_log.
[root@fc21 ~]# tail -f /var/log/httpd/error_log

[Fri Jan 09 08:31:50.859976 2015] [core:notice] [pid 6757] AH00052: child pid 6775 exit signal Segmentation fault (11)
I decided to use GDB to see where the segmentation fault occur.
[root@fc21 ~]# systemctl stop httpd
[root@fc21 ~]# systemctl status httpd
To start GDB.
[root@fc21 ~]# gdb httpd
(gdb) r -DONE_PROCESS
Program received signal SIGSEGV, Segmentation fault.
0x00007fffe7f431e8 in _zend_mm_free_int () from /etc/httpd/modules/libphp5.so
And it displayed the fault occured in zend_mm_free_int. Proceed with a "where".
(gdb) where
#0  0x00007fffe7f431e8 in _zend_mm_free_int ()
   from /etc/httpd/modules/libphp5.so
#1  0x00007fffe7f629ce in convert_to_double ()
   from /etc/httpd/modules/libphp5.so
#2  0x00007fffe0d20ea1 in zif_trader_stoch (ht=,
    return_value=0x7ffff7f257f8, return_value_ptr=,
    this_ptr=, return_value_used=)
    at /root/trader-0.3.0/functions/trader_stoch.c:67
#3  0x00007fffe7f5bf2a in dtrace_execute_internal ()
   from /etc/httpd/modules/libphp5.so
#4  0x00007fffe8019800 in zend_do_fcall_common_helper_SPEC ()
   from /etc/httpd/modules/libphp5.so
#5  0x00007fffe7fa9dd0 in execute_ex () from /etc/httpd/modules/libphp5.so
#6  0x00007fffe7f5bdc8 in dtrace_execute_ex ()
   from /etc/httpd/modules/libphp5.so
#7  0x00007fffe7f6e7c0 in zend_execute_scripts ()
   from /etc/httpd/modules/libphp5.so
#8  0x00007fffe7f0a6cb in php_execute_script ()
   from /etc/httpd/modules/libphp5.so
#9  0x00007fffe801b3c2 in php_handler () from /etc/httpd/modules/libphp5.so
#10 0x00005555555942f0 in ap_run_handler ()
#11 0x0000555555594839 in ap_invoke_handler ()
#12 0x00005555555a966a in ap_process_async_request ()
To continue, enter "cont".
(gdb) cont
Continuing.

Program terminated with signal SIGSEGV, Segmentation fault.
GDB is a useful tool to identify where fault lies. Maybe you could be one to raise a bug in php/httpd/linux with this. And for this problem, I actually found out that I need to cast a decimal in a php variable.
array_push($high,number_format($obj["high"],2,'.',''));

Wednesday 16 April 2014

Install opcache for php on Fedora

OPcache improves PHP performance by storing precompiled script bytecode in shared memory, thereby removing the need for PHP to load and parse scripts on each request #1. OpCode Caches are a performance enhancing extension for PHP. They do this by injecting themselves into the execution life-cycle of PHP and caching the results of the compilation phase for later reuse. It is not uncommon to see a 3x performance increase just by enabling an OpCode cache #2.

To install on Fedora:

yum install php-opcache 

To turn on the opcache module, restart httpd service:

/bin/systemctl restart  httpd.service 

You will be able to see opcache running information in phpinfo.php.

Tuesday 23 April 2013

PHP: Enable zlib output compression

You can enable php compression as it have a lot of benefits. It reduces the web traffic from host provider to your web. It speeds up the loading of your pages on clients PC. And it is supported by all newer web browser. All you have to do is to set "zlib.output_compression=on" in php.ini:
zlib.output_compression=on

Thursday 11 April 2013

Install APC (php) on Fedora 18

The Alternative PHP Cache (APC) is a bytecode optimization opcode cache for PHP. This free cache leads to faster runtime execution as it stores the final, compiled result in shared memory. To install APC, you can setup using YUM.
[root@localhost ~]# yum install php-pecl-apc
Using YUM method, it will create /etc/php.d/apc.ini , enabling apc extension module "extension = apc.so". If apc.ini is not found, you can insert "extension = apc.so" into php.ini. After apache restart(service httpd restart), you will see apc enabled in phpinfo.php. APC,cache,phpinfo

Monday 8 April 2013

How to display memcache statistics with php

To display memcache statistics, you can create a php script as shown below. This scripts uses "getStats" command to display the statistics. You can also format it into a html table.

<?php
$memcache_host="127.0.0.1";
$memcache_port="11211";
$memcache = new Memcache;
$memcache->connect($memcache_host,$memcache_port) or die ("Cannot connect");
$return=($memcache->getStats());
foreach ($return as $key => $value) {
    echo $key." : ".$value."<br>";   
}
?>

How to use memcache with php


Previously I posted an article on how to install Memcache. This time I will show how to use Memcache with PHP. This program will start off with a SQL query statement, hashing the statement and check if the data is stored in memcache.If found, the data will be retrieve from memcache. If it is not found in memcache, then it will query from MySQL database.


<?php
require('connect_db.php'); 
$memcache_host="127.0.0.1";
$memcache_port="11211";
$memcache = new Memcache;
$memcache->connect($memcache_host,$memcache_port) or die ("Cannot connect");

$version = $memcache->getVersion();
echo "Version: ".$version;

$query="select * from exampleDB limit 1;";
$key = md5($query); 
$get_result = $memcache->get($key);

if ($get_result) {   
    print_r($get_result);
    echo "Data retrieved from memcache";
}
else {    
    $result = mysql_query($query);
    if (!$result) {
        die('Invalid query: ' . mysql_error()) 
      }
    $row = mysql_fetch_array($result);
    print_r($row);  
    $memcache->set($key, $row, MEMCACHE_COMPRESSED, 10); 
    echo "Data retrieved from database";
}  
?>

Tuesday 26 March 2013

Compare php 5.3 vs 5.4

How much faster is php5.4 compared to php5.3? It was benchmarked , 5.4 is almost twice as fast as 5.3. PHP 5.4 significantly improves performance, memory footprint and fixes over 100 bugs.

PHP 5.4.0 offers a wide range of new features:

Support for traits has been added.
Short array syntax has been added, e.g. $a = [1, 2, 3, 4]; or $a = ['one' => 1, 'two' => 2, 'three' => 3, 'four' => 4];.
Function array dereferencing has been added, e.g. foo()[0].
Closures now support $this.
<?= is now always available, regardless of the short_open_tag php.ini option.
Class member access on instantiation has been added, e.g. (new Foo)->bar().
Class::{expr}() syntax is now supported.
Binary number format has been added, e.g. 0b001001101.
Improved parse error messages and improved incompatible arguments warnings.
The session extension can now track the upload progress of files.
Built-in development web server in CLI mode.

Upgrade php53u to php54 on CENTOS5

To upgrade php53/php53u to php54 on CENTOS5.

Enable IUS and EPEL:

[root@example ~]# rpm -Uvh http://dl.iuscommunity.org/pub/ius/stable/CentOS/5/x86_64/ius-release-1.0-10.ius.centos5.noarch.rpm
[root@example ~]# rpm -Uvh http://dl.iuscommunity.org/pub/ius/stable/CentOS/5/x86_64/epel-release-5-4.noarch.rpm


Install yum replace plugin:
[root@example ~]# yum install yum-plugin-replace
Upgrade php53 to php4:
[root@example ~]# yum replace php53u --replace-with php54
Verify php version:
[root@example ~]# php -v
Restart httpd:
[root@example ~]# service httpd restart

search iomeweekly