Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
R High Performance Programming
R High Performance Programming

R High Performance Programming: Overcome performance difficulties in R with a range of exciting techniques and solutions

Arrow left icon
Profile Icon Aloysius Shao Qin Lim Profile Icon Tjhi W Chandra
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.4 (14 Ratings)
Paperback Jan 2015 176 pages 1st Edition
eBook
$9.99 $19.99
Paperback
$32.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Aloysius Shao Qin Lim Profile Icon Tjhi W Chandra
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.4 (14 Ratings)
Paperback Jan 2015 176 pages 1st Edition
eBook
$9.99 $19.99
Paperback
$32.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$9.99 $19.99
Paperback
$32.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

R High Performance Programming

Chapter 2. Profiling – Measuring Code's Performance

The first step to improve the performance of R programs is to identify where the performance bottlenecks are occurring. To do this, we profile or measure the performance of an R program as it runs with respect to various measures such as execution time, memory utilization, CPU utilization, and disk I/O. This gives us a good idea of how the program and its parts perform, so that we can tackle the biggest bottlenecks first. This chapter will show you how to use a few simple tools to measure the performance of R programs.

The 80/20 rule is applied here. 80 percent of the possible performance improvements can usually be achieved by tackling 20 percent of the largest performance problems. We will look at how to determine which problems to solve first in order to get maximum improvement in the least amount of time and effort.

This chapter covers the following topics:

  • Measuring the total execution time
  • Profiling the execution...

Measuring total execution time

When people say that their program is not performing well, they are often referring to the execution time or the time it takes to complete the execution of the program. Execution time is probably the most important performance measure in many contexts as it is has a direct impact on people and processes. A shorter execution time means the R programmer can perform his or her analysis more quickly to derive insights faster.

It turns out that execution time is also the easiest performance characteristic that can be measured accurately and in detail (though not always the easiest to solve). Therefore, we will start learning about the way to profile an R code by learning to measure the execution time of R programs. We will learn three different tools to do this: system.time(), benchmark(), and microbenchmark().

Measuring execution time with system.time()

The first profiling tool we will learn about is system.time(). It is a very useful tool that we can use to measure...

Profiling the execution time

So far, we have seen how to measure the execution time of a whole R expression. What about a more complex expression with multiple parts such as calls to other functions? Is there a way to dig deeper and profile the execution time of each of the parts that make up the expression? R comes with the profiling tool Rprof() that allows us to do just that. Let's see how it works.

Profiling a function with Rprof()

In this example, we write the following sampvar() function to calculate the unbiased sample variance of a numeric vector. This is obviously not the best way to write this function (in fact R provides the var() function to do this), but it serves to illustrate how code profiling works:

# Compute sample variance of numeric vector x
sampvar <- function(x) {
    # Compute sum of vector x
    my.sum <- function(x) {
        sum <- 0
        for (i in x) {
            sum <- sum + i
        }
        sum
    }
    
    # Compute sum of squared variances...

Profiling memory utilization

Next, let's consider how to profile the memory utilization of R code.

One approach is to use Rprof() by setting the memory.profiling argument and the corresponding memory argument to summaryRprof():

Rprof("Rprof-mem.out", memory.profiling=TRUE)
y <- sampvar(x)
Rprof(NULL)
summaryRprof("Rprof-mem.out", memory="both")
## $by.self
##          self.time self.pct total.time total.pct mem.total
## "sq.var"      4.16    54.88       5.40     71.24    1129.4
## "my.sum"      1.82    24.01       2.18     28.76     526.9
## "^"           0.56     7.39       0.56      7.39     171.0
## "+"           0.44     5.80       0.44      5.80     129.2
## "-"           0.40     5.28       0.40      5.28     140.2
## "("           0.20     2.64       0.20      2.64      49.7
##
## $by.total
##           total.time total.pct mem.total self.time self.pct
## "sampvar"       7.58...

Monitoring memory utilization, CPU utilization, and disk I/O using OS tools

Unlike execution time, R does not provide any good tools to profile CPU utilization and disk I/O. Even the memory profiling tools in R might not provide a complete or accurate picture. This is where we turn to OS-provided system monitoring tools to keep an eye on the computational resources as we run R programs. They are task manager or resource monitor in Windows, activity monitor in Mac OS X, and top in Linux. When running these tools, look for the processes that represent R (usually called R or rsession).

The information that we get varies depending on the operating system, but here are the key measures of R's resource utilization to keep an eye on:

  • % CPU or CPU usage: The percentage of the system's CPU time used by R
  • % memory, resident memory, or working set: The percentage of the system's physical memory used by R
  • Swap size or page outs: The size of memory used by R that is stored in the operating...

Identifying and resolving bottlenecks

Now that we have covered the basic techniques to profile an R code, which performance bottlenecks should we try to solve first?

As a rule of thumb, we first try to improve the pieces of code that are causing the largest performance bottlenecks, whether in terms of execution time, memory utilization, or other measures. These can be identified with the profiling techniques covered earlier. Then we work our way down the list of the largest bottlenecks until the overall performance of the program is good enough.

As you can recall, the varsamp() example that we profiled using Rprof(). The function with the highest self.time was sq.var(). How can we make this function run faster? We can write it in the form of a vector operation my.sum((x - mu) ^ 2) rather than looping through each element of x. As we will see in the next chapter, converting loops to vectorized operations is a good way to speed up many R operations. In fact, we can even remove the function...

Measuring total execution time


When people say that their program is not performing well, they are often referring to the execution time or the time it takes to complete the execution of the program. Execution time is probably the most important performance measure in many contexts as it is has a direct impact on people and processes. A shorter execution time means the R programmer can perform his or her analysis more quickly to derive insights faster.

It turns out that execution time is also the easiest performance characteristic that can be measured accurately and in detail (though not always the easiest to solve). Therefore, we will start learning about the way to profile an R code by learning to measure the execution time of R programs. We will learn three different tools to do this: system.time(), benchmark(), and microbenchmark().

Measuring execution time with system.time()

The first profiling tool we will learn about is system.time(). It is a very useful tool that we can use to measure...

Left arrow icon Right arrow icon

Description

This book is for programmers and developers who want to improve the performance of their R programs by making them run faster with large data sets or who are trying to solve a pesky performance problem.

Who is this book for?

This book is for programmers and developers who want to improve the performance of their R programs by making them run faster with large data sets or who are trying to solve a pesky performance problem.

What you will learn

  • Benchmark and profile R programs to solve performance bottlenecks
  • Understand how CPU, memory, and disk input/output constraints can limit the performance of R programs
  • Optimize R code to run faster and use less memory
  • Use compiled code in R and other languages such as C to speed up computations
  • Harness the power of GPUs for computational speed
  • Process data sets that are larger than memory using diskbased memory and chunking
  • Tap into the capacity of multiple CPUs using parallel computing
  • Leverage the power of advanced database systems and Big Data tools from within R

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jan 29, 2015
Length: 176 pages
Edition : 1st
Language : English
ISBN-13 : 9781783989263
Category :
Languages :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Jan 29, 2015
Length: 176 pages
Edition : 1st
Language : English
ISBN-13 : 9781783989263
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 142.97
Mastering Predictive Analytics with R
$54.99
Mastering Scientific Computing with R
$54.99
R High Performance Programming
$32.99
Total $ 142.97 Stars icon
Banner background image

Table of Contents

11 Chapters
1. Understanding R's Performance – Why Are R Programs Sometimes Slow? Chevron down icon Chevron up icon
2. Profiling – Measuring Code's Performance Chevron down icon Chevron up icon
3. Simple Tweaks to Make R Run Faster Chevron down icon Chevron up icon
4. Using Compiled Code for Greater Speed Chevron down icon Chevron up icon
5. Using GPUs to Run R Even Faster Chevron down icon Chevron up icon
6. Simple Tweaks to Use Less RAM Chevron down icon Chevron up icon
7. Processing Large Datasets with Limited RAM Chevron down icon Chevron up icon
8. Multiplying Performance with Parallel Computing Chevron down icon Chevron up icon
9. Offloading Data Processing to Database Systems Chevron down icon Chevron up icon
10. R and Big Data Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.4
(14 Ratings)
5 star 57.1%
4 star 28.6%
3 star 7.1%
2 star 7.1%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




adnan baloch Mar 09, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book deserves to be on the shelf of any serious R user. The author explains the details of R's inner workings so the readers get a good idea about its limitations. Benchmarks are the mainstay of any performance enthusiast. The author dedicates an entire chapter to helping readers understand how to measure the performance of their code so they can quickly find out if they are on the right track when tuning their code for speed. Sometimes the best optimizations are simple ones. Such tweaks get their own chapter in the book. As any programmer knows, compiling is the quickest way to make code fly. Excellent coverage of this aspect is provided by the author. With the proliferation of GPU's in every new PC, serious data scientists now have another weapon in their arsenal. The author shows us how to take the GPU out for a ride and unleash its power. Not all tasks are best suited for GPU's so the author explains how to ensure that the right processing unit is used for the right job. Getting the best out of R by making the most of available RAM, supercharging R with parallel computation, using databases to assist in processing tasks and stepping into the world of Big Data are also explored by the author and promise to take the reader's R expertise to a whole new level.
Amazon Verified review Amazon
Arda Apr 13, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is a great book covering almost all approaches you may want to take when you need to squeeze some more performance out of your existing R code. It covers almost all aspects of optimization, from reducing time complexity of your applications (ie, profiling, identifying bottlenecks, using compiled code for bottlenecks, using GPUs etc) to reducing space complexity (memory optimization, tweaks for working with resource restrained systems) to horizontal scaling. The last step (RHadoop) can be a good stepping stone if all else fails and you need to use a distributed solution.
Amazon Verified review Amazon
ruben Apr 11, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Hello very interesting book important topics that programmers do not gave follow in the R programming procedures.I like all the chapters because it explain the basics so we can go on doing and applying the main concepts.In my opinion the kind of topics rarely don't cover in a regular class so for me that I used this informstion it was a nice experience to teach this kind of information very helpful.Thanks.
Amazon Verified review Amazon
Massera Riccardo Mar 04, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
R High Performance Programming is an excellent book to help R programmers to take advantage of all the features of the language and solve practical performance problems or bottlenecks that they might encounter processing large amounts of data.Every chapter explains a topic with simple but meaningful examples,showing which tools to use and how to pick the right packages from CRAN.The reader is also given the choice to only read certain chapters if he does not want to delve into the more advanced topics.The book starts by introducing the reader to R features, the language internals and its memory model.The authors then explain how to correctly measure code performance and the basic tricks that can be adopted when coding an R program to ensure code runs fast and does not waste computing resources.After this introductory part, the book deals with a set of advanced techniques to get your programs running even faster, like developing code compiled for R, accelerating the computation by taking advantage of the GPU, optimizing the memory footprint and processing large datasets with limited resources.For scenarios where the previous techniques are not sufficient, the last chapters deal with parallelization or R programs, offloading the processing to a database and dealing with Big Data with an example running on AWS.In conclusion, I really enjoyed reading this book because it is written in a very simple and understandable manner also for less experienced programmers and even complex subjects are explained in a simple way.
Amazon Verified review Amazon
A. Zubarev Feb 22, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
R High Performance Programming is probably a unique book in terms of the material covered, I just have not see yet to date a book that is dedicated to increasing the computational capacity of the R language.And I need to state frankly, since R has left the academic circles a long time ago and now is being used more and more in applications involving the Big Data calibre of projects a developer or an R user needs to understand its limitations and perhaps even be able to shrug off some misconceptions that surface on and off about the R’s Big Data suitability.This book will make you prepared to cope with those who encroach on R’s capability to process petabytes of data. Bedsides, since the authors have a very broad outlook on the technologies and succeeded to cover very difficult topics in simple terms this book actually is of an asset to any software developer, using any language on any platformWhat do you need for this book: preferably a *NIX based 64 bit machine capable enough to run a Virtual Machine with an NVIDIA GPU. An Amazon EWS account. Eclipse R Add on (R Studio was cited as storing object state). A Windows user will be able to learn as much, but some of the libraries covered in the book (just a few) were not ported to Windows at the time of my reading.Aloysius and William cover the code execution benchmarking techniques at the beginning very well and then make you embark on wonderful journey to exploring an array of CRAN packages, third party tools and frameworks, the book includes the use of Hadoop, PostgreSQL, MonetDB (vertical data store), Pivotal SciDB, and more so you will not be limited to a narrow subset of tools to use under your belt, it will be something like dirking from the firehose!I read this book in one breath, it is was just that a fascinating journey. I now think I need to come back, and read several chapters of immense interest to me: code pre-compilation (just so easy to take advantage of), the FF, dplyr and BigMemory package (just take advantage of somebody giving you a hand). I will experiment with at least one database, perhaps MonetDB as being at fingertips reach.If I had a small complaint that would be for the absence of the statistical visualizations code – I just would like to benchmark my own improvements.All in all, it is a fantastic book, thank you Aloysius and William! A very timely release Packt!My verdict, is it a superb reading!
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.