# R/Debugging

(Difference between revisions)
 Revision as of 00:07, 2 July 2009 (view source)Chloe (Talk | contribs)m (→Profiling: added link)← Older edit Latest revision as of 22:57, 25 October 2011 (view source)Chloe (Talk | contribs) (→Profiling) Line 15: Line 15: Keep in mind the 2 rules of performance optimization, ''"The First Rule of Program Optimization: Don't do it. The Second Rule of Program Optimization (for experts only!): Don't do it yet."'' [http://en.wikipedia.org/wiki/Optimization_(computer_science) by] Michael Jackson, and these [http://www.cs.cmu.edu/~jch/java/rules.html basic principles]. If you are going to optimize your code, it's critical to profile it first, as our intuition as to what is slow is often wrong.  '''[http://www.stat.ucl.ac.be/ISdidactique/Rhelp/library/base/html/Rprof.html Rprof]''' is a function in R that lets you profile a function. Keep in mind the 2 rules of performance optimization, ''"The First Rule of Program Optimization: Don't do it. The Second Rule of Program Optimization (for experts only!): Don't do it yet."'' [http://en.wikipedia.org/wiki/Optimization_(computer_science) by] Michael Jackson, and these [http://www.cs.cmu.edu/~jch/java/rules.html basic principles]. If you are going to optimize your code, it's critical to profile it first, as our intuition as to what is slow is often wrong.  '''[http://www.stat.ucl.ac.be/ISdidactique/Rhelp/library/base/html/Rprof.html Rprof]''' is a function in R that lets you profile a function. + + Rprof() + + mySlowFunction(1000) + + Rprof(NULL) + summaryRprof() + ===Ways to use Rprof's output=== ===Ways to use Rprof's output===

## Interactive Debugging in R

Often times when we write our own functions, or use other functions in various packages, the error messages can sometimes get confusing. While good programming practice and patience are keys to solving these problems, R also has some other tools that can be used to make the debugging process, which is critical in any programming assignment, as engaging and smooth (and even fun!) as possible.

The most useful debugging functions are

• traceback
• debug
• trace
• options(error=recover)

Here is a very helpful reference on interactive debugging by Roger Peng, UCLA.

## Profiling

Keep in mind the 2 rules of performance optimization, "The First Rule of Program Optimization: Don't do it. The Second Rule of Program Optimization (for experts only!): Don't do it yet." by Michael Jackson, and these basic principles. If you are going to optimize your code, it's critical to profile it first, as our intuition as to what is slow is often wrong. Rprof is a function in R that lets you profile a function.

```Rprof()

mySlowFunction(1000)

Rprof(NULL)
summaryRprof()
```

### Ways to use Rprof's output

High-Performance R: improving cpu time and memory use