First what is XHProf?

From: https://github.com/facebook/xhprofXHProf is a function-level hierarchical profiler for PHP and has a simple HTML based user interface. The raw data collection component is implemented in C (as a PHP extension). The reporting/UI layer is all in PHP. It is capable of reporting function-level call counts and inclusive and exclusive wall time, CPU time and memory usage.

From: http://pecl.php.net/package/xhprofXHProf: A Hierarchical Profiler for PHP
XHProf is a function-level hierarchical profiler for PHP and has a simple HTML based navigational interface. The raw data collection component is implemented in C (as a PHP extension). The reporting/UI layer is all in PHP. It is capable of reporting function-level inclusive and exclusive wall times, memory usage, CPU times and number of calls for each function. Additionally, it supports ability to compare two runs (hierarchical DIFF reports), or aggregate results from multiple runs.

There are a number of ways to profile and monitor the performance of PHP code in a development environment, but once it’s been let loose on a production server its extremely difficult to know what’s going on when your app is getting accessed by your users.
In March 2009, Facebook released XHProf, a function level profiler that allows you to identify bottlenecks in your application. And it runs on a production server with little overhead.
XHProf will provide you with a hierarchical profile of the functions your application calls, allowing you to follow the chain of events that lead up to resource intensive code running. You’ll be able to see exactly how much wall time (the actual time elapsed), CPU time and memory your application uses.
This tutorial will help you get XHProf installed on your server, and integrated with your CodeIgniter application via hooks so that you can start profiling your application, in a production environment, straight away. Everything you see here was written for Ubuntu 12.04:

Installation of XHProf can be done via PECL – as per php manual, it’s very hectic get the PECL version installed on Ubuntu. For me it’s easier to install from source.

So here I will explain how to install from source. To install from source we will require “phpize” pecl extension. So first we will install phpize.

In this topic I am assuming a PHP web server running with (Apacpe and PHP).

Step 1.) How to install phpize on ubuntu?

On Debian/Ubuntu, it’s in the php5-dev package, so we will install php dev package.

$ sudo apt-get install php5-dev

It will be available here: /usr/bin/phpize instead of only phpize.

The php5-dev package contains various files absolutely essential to compiling PHP. Since it’s a shell script, you can just copy it from the package, but it won’t work without the dependencies for building a PHP extensions (like header files).

Explanation

In the C world, compiling dynamically linked libraries (DLL/SO) is done by using header files that contain the description on how the libraries are to be interacted with (function calls, structures, etc). These are used to compile an extension without the need for the PHP source code itself. In other words, you don’t need the PHP source but you actually need the header files which are contained in php5-dev.

Note: path of xhproff log dir must be php execute user accessible. Means it must be in /var/www/ dir or accessible to www-dada user as this www-data user execute php script and xhprof log are created by this www-data user.

Finally, we need to tell PHP to load the extension. Create a config file for it – I do this for cleanliness but you can always drop it at the end of your main php.ini.

$ sudo gedit /etc/php5/conf.d/xhprof.ini

And paste in the following:

extension=xhprof.so
xhprof.output_dir="/var/www/xhprof/log_data"

This tells XHProf to use the directory at /var/www/xhprof/log_data to save its run data.
Note: path of xhproff log dir must be php execute user accessible. Means it must be in /var/www/ dir or accessible to www-dada user as this www-data user execute php script and xhprof log are created by this www-data user.
You can check whether XHProf is installed correctly by entering php -m at the command line and checking that the module is available. Remember to restart Apache so that it gets picked up in your PHP web applications as well.

If you want to render the callgraph images you’ll also need the graphviz package. This can be obtained from apt.

XHProf can be used on an ad-hoc basis to evaluate small pieces of code, but it’s at its most useful when you let it profile the full page. First of all, you’ll need to move the XHProf code into your web applications root so that it has access to the appropriate classes.
This already explained in 2nd setup, but again I will explain it.

Copy xhprof source to web dir (doc root folder) for viewing the logs and make log dir inside it or inside doc root to make www-data user accessible and also set writable permission to www-data user. This has been done in 2nd step so it must not be done again.

Note: path of xhproff log dir must be php execute user accessible. Means it must be in /var/www/ dir or accessible to www-dada user as this www-data user execute php script and xhprof log are created by this www-data user.

CodeIgniter has an excellent mechanism for injecting custom code into the execution of a page called ‘Hooks’. This is what we’ll use to integrate XHProf with your application.
Enable hooks in your application/config/config.php file.

• The $XHProfPath variable should point to the directory you installed XHProf in as explained in step 2 and also above in this step. In our example, we put it in the root of the web application, but you might be storing it somewhere central and symlinking it to multiple applications.
• The $applicationName variable lets you specify the name of the application using XHProf. This could be especially important in an environment where you’re running multiple applications on the same server.
• The $sampleSize variable lets you specify a factor for how often XHProf profiles a run. In a production environment where you’re receiving thousands of hits, it’s probably not worth storing every single run. You can increase this variable to get a random sample of runs. Changing it to 10, for example, will give you a report from one in every 10 visits to your application.

The xhprof_enable() function can accept any combination of 3 constants.

• XHPROF_FLAGS_NO_BUILTINS – skip all internal php functions. Adding this means you’ll only see time spent in functions that you have written (or are part of CodeIgniter)
• XHPROF_FLAGS_CPU – add additional CPU profiling information
• XHPROF_FLAGS_MEMORY – add additional memory profiling information
• Combine them using +. eg. xhprof_enable(XHPROF_FLAGS_NO_BUILTINS + XHPROF_FLAGS_MEMORY);
After running through your application a couple of times, point your browser at the XHProf application directory http://localhost/xhprof/xhprof_html/index.php – adjusting for the address of your development server – and you’ll see a list of your last application runs with the newest at the top. Select one of the runs to see its profiling information.

Evaluating the Results
Storing all this profiling information is all very well and good but knowing how to evaluate it is the key to optimizing your application.
The ‘Overall Summary’ is a good place to start – it’ll show you:
• Total inclusive wall time – how long (in microseconds) it took for you page to be generated
• Total memory use – the total memory used by this run of your application
• Total peak memory use – the maximum amount of memory that was used by your application
• Number of function calls – the number of functions that were called by your application

These numbers should give you an overall base to start from and provide headline numbers to compare against when you start optimization.
Below the summary is the detailed run report the bottlenecks in your application should be fairly obvious – they’re the function calls at the top of the report.

The most resource intensive things you’re likely to come across will be those that make calls to external services or your database. By default, the results are sorted by ‘inclusive wall time’. This shows the functions that took the longest to run by the cumulative total of them and the functions they call. Ordering by ‘exclusive wall time’ allows you to see the specific functions that are using the most amount of resource.
Clicking a function allows you to drill down into more detail about that function and the functions it called. From there, it’ll be easier to see exactly what your long running function was doing and spot any issues.
When debugging your CodeIgniter application, one of the best places to start is the controller being called for your page – Welcome::index in the example. From there you can easily see the breakdown of where the controller spent most of its time.

Callgraph
XHProf can generate a call graph view that provides a visual clue to the main path of your application. The main bottlenecks are highlighted in red to show where most your resources are being spent.

Comparing Runs
XHProf provides a mechanism for comparing multiple runs – this will allow you to make a number of optimizations and then see how they’ve affected your application.http://localhost/xhprof/xhprof_html/index.php?run1=run_id_1>&run2=run_id_2&source=applicationName
Note: run_id_1 and run_id_2 should be the ids from some of your previous runs and applicationName should be the name you specified when setting up the hook earlier.
This will provide the same information you see in a regular report but provide percentage statistics on any changes since the first run, allowing you to easily see if your optimizations are moving your performance in the right direction.

Aggregating Runs
Sometimes a single run might not be enough to evaluate exactly what’s going on. Pages my work slightly differently depending on the query string or user input or there might be differences in caching mechanisms.
Aggregating a number of runs allows you to combine a number of runs and receive an average of the resources consumed.http://localhost/xhprof/xhprof_html/index.php?run=run_id,run_id,run_id&source=applicationName
Note: run_id should be the ids from some of your previous runs and applicationName should be the name you specified when setting up the hook earlier.

Summary
You should now have XHProf up and running in your CodeIgniter application and be able to see exactly where your code is spending most of it’s time. Optimisation can be a difficult task. Sometimes it’s not as simple as reimplementing a function, or adding a layer of caching. Thinking about why you’re doing something and what the exact effect that is having on your application is just as important.
So let me know if you have any questions in the comments below. Thank you so much for reading!

Like this:

To measure the performance of a web site we need to get loading time of all classes and number of queries and execution time of each query etc.
In CodeIgniter it can be done very easy way. A very good part of CodeIgniter is its ability to give you the ‘profiling’ information for page loads. That is, if you add:

$this->output->enable_profiler(true);

In your controller before you load a view, CodeIgniter will give you information regarding how fast the page loaded, how many SQL queries executed, the content of each query, and the running time of each query. This is incredibly useful when you are trying to debug your application, or simply see how quickly things are loading.

There’s only one problem: To enable profiling, that line of code above must be present. What if you want to profile several pages, or even your whole web application? In that case, you have to start thinking:

I could put that line in the constructor of my controller, and then of of that controller’s methods will be profiled.
I could put that line in each method I want to profile.

These methods start to get ugly. And of course, you don’t want to comment out each profiling line when you don’t need them.

I will suggest to tackle this problem using CodeIgniter’s Hooks feature to enable or disable profiling for the entire web applications based on a value in the configuration file. In the end, I can turn on profiling for my entire website via a config value by setting it to true or false.

Developers love to automate things—for every process between development and production, they are keen to have a script that makes their workflow easier. This is also the case with deployment. The process of pushing the final build and deploying the app should be as easy as pressing a Deploy now button, but that is not what happens most of the time. We end u […]

Storing your app's data in the cloud is very important these days because users tend to own multiple devices and want their apps to be in sync across all of them. With Cloud Firestore, a real-time NoSQL database available on the Firebase platform, doing so is easier and more secure than ever before.In an earlier tutorial, I introduced you to all the pow […]

We started this series by learning how to animate HTML elements using mojs. In the second tutorial, we moved on to animation of built-in SVG shapes using the Shape module. The third tutorial covered more ways of animating SVG shapes using the ShapeSwirl and stagger modules.Now, we will learn how to animate different SVG shapes in a burst formation using the […]

This tutorial will give an introduction to JSON Web Tokens (JWT) and how to implement JWT authentication in Django.What Is JWT? JWT is an encoded JSON string that is passed in headers to authenticate requests. It is usually obtained by hashing JSON data with a secret key. This means that the server doesn't need to query the database every time to retrie […]

In this post, you'll learn what ExpoKit is and how it is used for adding native functionality to Expo apps. You'll also learn some of its pros and cons. In my Easier React Native Development With Expo post, you learned about how Expo makes it easier for beginners to begin creating apps with React Native. You also learned that Expo allows developers […]

What You'll Be CreatingIntroduction A lot of articles, our site included, have focused on helping readers create amazing iOS apps by designing a great mobile user experience (UX). However, with the emergence of the Apple Watch a few years ago, alongside CarKit, and more recently the HomePod this year, we are starting to see a lot more apps and IoT appli […]

If you're ready to take your WordPress skills to the next level and get your feet wet with PHP, you'll love our newly expanded course, Learn PHP for WordPress.What You’ll LearnIn this course, Envato Tuts+ instructor Rachel McCollin will give you an overview of what PHP is and how it's used for WordPress themes and plugins, with examples. You […]

Application widgets provide your users with easy access to your application’s most frequently used features, while giving your app a presence on the user’s homescreen. By adding a widget to your project, you can provide a better user experience, while encouraging users to remain engaged with your application, as every single time they glance at their homescr […]

It wasn't very many years ago when everyone was trying to make a quick buck on a blog. Fast-forward just a few years, and the entire scene has changed radically.Selling advertising on a website isn't as easy as it once was. The "Golden Age of Blogging" has certainly passed, but that doesn't mean monetization has come to an end. It si […]

OverviewThis is part two out of two in a series on cleaning up data using Go. In part one, we covered the basic text facilities of Go and working with CSV files. In this tutorial, we'll dive into actual data cleaning. We'll start by understanding the problem of messy data and coming up with a strategy, and then we'll look into verifying indivi […]

Here’s wishing all of you a very happy and prosperous new year. I’ve been writing rather infrequently in 2009 and thats likely to continue into the first couple of months in 2010. I’m going to be in Ahmedabad around 15-20 th Jan. If anyone wants to meetup, drop me an email. CommentsJanuary 4, 2010, Rama [...]

VoiceTap is a Noida based startup that hopes to connect knowledge seekers with knowledge experts. As the fast-food content on the Internet grows, its becoming more and more difficult to search for relevant, precise, authoritative answers to your questions on Google. VoiceTap hopes to make it easier for those seeking answers to questions to connect [...]

MumbaiTrader is a new startup, offering social investing tips to Indians. The site brings together a network of pre-screened and verified advisors, who will offer their services to investors. Each advisor is ranked and investors can opt to follow an adivsor based on their rating and track record. This Covestor like model has been implemented [...]

Vikas Bajaj has a story on NYT about India’s slow pace of innovation. Nothing new and nothing most of you all didnt know already. Even the ubiquitous Sujai Karampuri gets a mention as is normally the case on stories based on this theme (no offense to Sujai – I love his blog and admire how [...]

Since August, Rediff has lost four key executives - – Long time product head – Zaki Ansari – who quit in August to join UTV New Media – India Abroad editorial director Prem Panicker quit to join Yahoo India – CFO Joy Basu left in August – Most recently, Salil Chandrashekar, director of product development [...]

I recently uncovered an incident where Burrp seems to have deleted a user review. Nishith, founder of Pune based True Sparrow Systems (team behind SocialMedian – acquired by Xing), wrote a review for a Pune based burger joint, which he tweets was deleted by Burrp. While I havent seen this as frequently occurring scenario, I [...]

I’m looking for some data entry work to be done — can you recommend a reliable service provider if you’ve used one ? Leave a comment or drop me an email – contact [at]startupdunia[dot]com. CommentsDecember 8, 2009, Neelabh Prabhat commented: Hi, We have started a rural BPO in collaboration with the CSR arm of Usha [...]

Overall Learnings There is no problem, i.e., (1) there are not enough good problems that startups are working on (2) there seems to be no shortage of funds, platforms and ecosystem partners willing to help startups, there are not enough good startups for them to support. The ecosystem is hungry for successes. It was a [...]

VCCircle reports that Infy co-founder, NR Narayana Murthy, has sold $37 million worth of Infy shares to setup a VC fund. Proceeds from the sale will be used as seed capital for the fund. That is great news. He has amazing street cred and is definitely viewed as an entrepreneurial icon who grew Infy to [...]

Although I’ve been tempted to own an iPhone since the day it launched, I’d held off doing so because AT&T is the sole carrier in the US and frankly – AT&T simply sucks. However, I finally caved in and got myself one a couple of weeks ago. First and foremost – there’s no denying that [...]

Ofgem, the U.K. government’s regulator for gas and electricity, has revealed that projects trialled under the Low Carbon Networks Fund (LCNF) could save 215 tonnes of CO2. The program ran for six years, ending in 2015, with the aim of helping Distribution Network Operators (DNOs) develop cost effective and energy efficient solutions for the smart... Read mor […]

The Internet of Things is sweeping across the globe at breakneck speeds, and before we know it, our entire lives will be facilitated by connected technology. We’re already seeing the IoT make an incredible impact on how the industrial world operates, and we’re seeing it seep into household goods to bring convenience and efficiency to... Read more » The post […]

PARC, the research and development arm of Xerox, announced on Tuesday that it has secured part of $19 million in federal funding from the Energy Department to develop peel-and-stick sensors for homes, businesses, and other buildings. The peel-and-stick sensors will be able to detect air quality, temperature, humidity, occupancy, and more, according to PARC. […]

Studies of traffic congestion regularly point much blame at cars circling for parking. To tackle this perennial problem, Get My Parking is joining a smart city initiative to launch a smart parking pilot in India. As reported in Firstpost, the Delhi-based startup’s technology is being tested in government smart city initiatives. “We are getting a... Read more […]

According to a recent Gartner survey, almost a third of fitness tracker or smartwatch owners end up ditching them. The survey studied about 9,000 users from the U.S., Australia and the U.K. Reasons for the dropped tech use vary from wearables breaking, to just becoming bored of them. “Dropout from device usage is a serious... Read more » The post Do fitness […]

An increasing number of farm fires are being caused by electrical arc faults, a high-power discharge of electricity between two or more conductors. Nare IoT Labs, a South Korean startup, has developed a cost effective solution to prevent and warn farmers of any faults, before the fire starts. The system, called “Prevention System for Electrical... Read more […]

A new report says Google has spun out its self-driving unit — now called Waymo — and is undertaking a major pivot away from making its own autonomous vehicles, instead moving to become a provider of self-driving car tech for major automakers. These Google car revelations revealed in a lengthy report on tech site The... Read more » The post Google’s Waymo to […]

Scotland’s seven major cities are teaming up to develop a number of smart city projects, backed by a $31 million war chest. According to Scottish Construction Now, the seven cities will springboard off the funding to collaboratively develop themselves into future-capable digital hubs. See also: Outdated thinking on wireless could doom UK smart cities The... […]

With trends like ride sharing, autonomous vehicles, and the connected car, the auto industry is increasingly in the spotlight. As drivers contemplate letting computers take over control of the wheel for them, it brings up some important questions. What will cars of the future look like? What things will drivers be able to accomplish on... Read more » The pos […]

Several months ago, CCS Insight surveyed 2,000 people in the US and UK about what they would most like to have tracked about themselves, and a large portion of them answered with, “stress levels.” It looks as though their requests are being answered. Mental health is a big focus in the tech industry right now.... Read more » The post Tech world aims to tack […]