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

Thursday, October 20, 2011

Parallel Processing benchmark in PHP ( CURL version )

Introduction
There are so many tools that gives PHP the capabilities of parallel processing.  Well, not multiple threads, but multiple processes, the outcome is very similar though, it makes PHP do several things at the same time without blocking.

Tools you can find today that I can think of :-
  • Gearman
  • Fork (pcntl_fork)
  • curl_multi
  • rolling curl ( just another flavor of curl_multi )
  • various Message Queue, like Rabbit MQ.

But this post is focusing on comparing / benchmarking "curl_multi" and "rolling curl",  since in general "rolling curl" is believed to be more efficient than "curl_multi" without doing the rolling. However, the benchmark result is quite confusing me.

Note: "Rolling Curl" at the end is still using curl_multi, but the difference is it swap out (roll out) finished job instead of waiting for the longest job to return.  For example, in this way, you don't need to wait for everything to finish before processing your returned data.

Benchmark Starts Here
I'm trying to do a benchmark between using Rolling Curl v.s. normal implementation of curl_multi (without the rolling).  The result is very close, but quite a number of time it shows that Rolling Curl is actually slower.

What I did is having both doing the same thing, "curl" 20 different urls and count 0 to 500 after the job is done. I try to simulate 5 concurrent users to call the script for 10 times.   And here is the result I get back.

Rolling Curl

Transactions:            50 hits
Availability:        100.00 %
Elapsed time:         44.57 secs
Data transferred:         0.00 MB
Response time:          4.08 secs
Transaction rate:         1.12 trans/sec
Throughput:          0.00 MB/sec
Concurrency:          4.58
Successful transactions:          50
Failed transactions:            0
Longest transaction:         9.54
Shortest transaction:         1.78

curl_multi without rolling

Transactions:            50 hits
Availability:        100.00 %
Elapsed time:         39.11 secs
Data transferred:         0.00 MB
Response time:          3.51 secs
Transaction rate:         1.28 trans/sec
Throughput:          0.00 MB/sec
Concurrency:          4.49
Successful transactions:          50
Failed transactions:            0
Longest transaction:         8.96
Shortest transaction:         1.94

At first I'm thinking the Rolling Curl will be faster since it will do the counting whenever a particular "curl" is done and rolled out.  However, it looks like the benchmark is telling us that it is faster without rolling the curl.  The following is the testing script I'm using to compare with Rolling Curl.

Is there something I'm missing when I use this testing script??  Any thoughts??



// testing function
function multiple_curl_request($nodes){ 
        $mh = curl_multi_init(); 
        $curl_array = array(); 
        foreach($nodes as $i => $url) 
        { 
            $curl_array[$i] = curl_init($url); 
            curl_setopt($curl_array[$i], CURLOPT_RETURNTRANSFER, true); 
            curl_multi_add_handle($mh, $curl_array[$i]); 
        } 
        $running = NULL; 
        do { 
            usleep(1000); 
            curl_multi_exec($mh,$running); 
        } while($running > 0); 
        
        $res = array(); 
        foreach($nodes as $i => $url) 
        { 
            $res[$url] = curl_multi_getcontent($curl_array[$i]); 
            for($i = 0; $i < 500; $i++) {
                // just counting and do nothing
            }
        } 
        
        foreach($nodes as $i => $url){ 
            curl_multi_remove_handle($mh, $curl_array[$i]); 
        } 
        curl_multi_close($mh);        
        return $res; 
} 



Reply from Josh ( Author of Rolling Curl )
I bench marked Rolling Curl when I first wrote it and it was significantly faster.  Of course, since you're measuring things on the open web, there are lots of variables that come into play...  is the network just slow, are you overloading your own server, etc.  Keep in mind, the benefits of rolling curl mostly show up when you are dealing with large data sets.

I'd be interested to see the full code you used for your bench mark, although I won't have time to debug it for you.  

For a good benchmark, I would suggest you download the Alexia top 1,000 sites using regular curl_multi and compare the results with downloading the same list using rolling curl.  I think you will see the difference -- ie. regular curl_multi will probably choke on you.

Wednesday, October 12, 2011

Caching with Memcache and APC

If you are doing PHP, you should be knowing what is cache and different type of cache strategies.  I bumped into this slides when I was comparing (or precisely documenting) different type of cache strategies.  This slide is focusing on Memcahe and APC, and when/why/how to use them.


Friday, October 7, 2011

How to hack Apache Server

Got an internal email about a "security thread" in Apache Server, and someone send me this link as well.


Saturday, September 10, 2011

Basic Linux commands for LAMP developer

Came across this blog recently, and found it's quite useful.  It covers some basic useful commands that a LAMP developer may need to use from day to day.


http://www.addedbytes.com/blog/basic-linux-command-line-tips/


Besides the list above, let me include some of which I think all LAMP developer should have known.  [ Note:  I'm not including any advanced commands here, since this post is about basic only. ] 


wget - for retrieving stuff
wget http://somewhere.com/release/stuff-0.0.13/stuff.tgz
scp - copy stuff in ssh way
scp fileA.tgz me@yourhostname:/path/you/want
rsync - it keeps an index of sync files which decrease the bandwidth usage when transferring ( yes, dump ftp )
rsync -avu  -e ssh ~/path/to/stuff me@hostname:/path/to/sync-with
top - check running process status, the basic usage is to check which process is taking the most memory, for example.


tar - backup by creating tarball, and you can use with other params to create tgz ( tar gzip ), for example.


alias - create alias for your commands, this will save you tons of time.


export - export a shell variables in your current session.


find - find files
find /mp3-folder -name 'Celio*' -and -size +10000k 


Please don't ask me why you don't see "mv, ls, rm, mkdir ... etc".  Those are not should know, those are MUST know for LAMP developer.


Please feel free to add (comment) what you think the basic commands that we all should know and is not listed above. 

Thursday, April 21, 2011

String conversion to numbers

I came across the PHP documents today on Type Juggling and String conversion and find this interesting behavior.

$result = 10 + "10 pigs";  // integer(20);
$result1 = "10.0 people" + 10';  // float(20.0);

The "+" sign is an automatic type conversion operand.  Just like the example above, it doesn't care if you have non-numeric string inside your "string", it will convert to numbers for you.  The catch is, the number in a string must be occurred first, it won't work if the numeric value sits in the middle of the string.

According to the PHP document,
A valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.

For further readings, here are the links:



Tuesday, April 19, 2011

How cookie works

A lot of developers know how to get / set cookie to persist their application, however, not necessarily all of them know how cookie actually works.  Here is a short tutorial on how cookie works.

When your browser send a request to a website "A", your client (browser, for example) will contact server "A" for contents.  Your browser will look on your machine whether a cookie that has been set by "A".  If it finds the "A"'s cookie, your browser will send all those related name-value pairs in the file to "A" as HTTP headers. If it didn't find the file, it won't send any cookie data ( well, that's obvious ).  After that, the "A" website can use the cookie that the browser send, and "A" can set additional cookies for future use.  Also, the cookie is a text string that is include in the request and response, that's how "A" can interact with your browser.


The following is a more visualize version of how cookie is set and get:

1) when you request a server by url a http requst will be sent ( assume this is the first time access )
============================
GET /index.html HTTP/1.1
Host: www.abc.com
============================

2) when server response, it will have something like that
============================
HTTP/1.1 200 OK
Content-type: text/html
Set-Cookie: name=iroy2000
============================

3) now the browser request the same page again
============================
GET /index.html HTTP/1.1
Host: www.abc.com
Cookie: name=iroy2000
Accept: */*
============================

Extra Note about Cookie
What's the difference between "session" and "cookie" ?
There are two kinds of cookies: session cookies and persistent cookies. The session cookies are stored in memory on the server, whereas persistent cookies are stored in a cookie file on the client.

Some developers, when they first start, may be confused about "session" and "cookie".  In short, "cookie" is saved in the client's browser and can last for a long time (it first saved in browser memory - "temp cookie", but if you set a long time-to-live value, the cookie will be saved into a file - "permanent cookie" ) , while "session" is saved in the server and only valid for a browser session.

What is a persistent (permanent) cookie?
A persistent cookie is a cookie which is stored in a cookie file permanently on the browser’s computer. By default, cookies are created as temporary cookies which stored only in the browser’s memory. When the browser is closed, temporary cookies will be erased. You should decide when to use temporary cookies and when to use persistent cookies based on their differences:
  • Temporary cookies can not be used for tracking long-term information.
  • Persistent cookies can be used for tracking long-term information.
  • Temporary cookies are safer because no programs other than the browser can access them.
  • Persistent cookies are less secure because users can open cookie files see the cookie values.

And depends on your architecture and your use case,  one method may be more preferable than the other one. Let me list some points that you should consider:

  1. How many servers you run your website?  Remember that "session" is saved in the server (yes, a server, not multiple server), so it means if you have more than one server in your cluster, you need to maintain the "session" for a particular user.  Usually people sync the "session" using the database, and I believe apache's mod_proxy provide sticky session that maintain sessions in multiple server settings.  However, cookie is saved in browser, so it won't care how many servers at your back.
  2. How sensitive is your data?  Since "cookie" is save in your local machine, it means your user could potentially modify those data.  For example, firefox users can modify their cookie values.  If you do not want your user to modify the information, and if the data is sensitive, it is recommended that you should not use cookie to hold the data, but instead, try to hold sensitive data in database and use cookie to hold the ID for future retrieval. 
  3. How long you need your data? Well, as mentioned above, session is for a browser session, cookie is for longer term.
  4. How large is your data? Cookie since it is saved in the browser, it has a size limitation, if you are going to store big amount of data, you should consider session or database, because these both saved in a server and has more generous limitation than session.