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
$9.99 $19.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.4 (14 Ratings)
eBook 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
$9.99 $19.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.4 (14 Ratings)
eBook 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 eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

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 : 9781783989270
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Jan 29, 2015
Length: 176 pages
Edition : 1st
Language : English
ISBN-13 : 9781783989270
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

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.