While the New Relic Mobile agent comes ready to grab a bunch of timing information for your app right out of the box, sometimes you’ll want to add your own custom timers. Perhaps you want to know the length of time it takes for a user to click through a menu. Maybe you want to compare the average time between two particular button taps. You may even want to know how long a user stares at a particular view controller.
Enter the NRTimer class. This is what we use under the hood to track the duration of all things Mobile. Better yet, it’s available for you to use as part of the SDK! Creating a timer is super simple and once you’ve collected that data, it is super easy to work with and display using Insights. I’ll be using Swift in this particular example, but the concept is nearly identical for Objective-C and Java for Android.
Let’s say I want to know how long it takes my application to launch. I consider my app to be fully launched once the user is looking at the the first view controller, after it has completely loaded. To get that time, I take the following steps:
Create An NR Timer
An obvious first step. We need to create a custom
NRTimer()object to use for our timing metric. I’m going to persist this in the appDelegate so we can start the timer ASAP and then access it once we arrive at the initial view controller.
Start the Clock
Start the timer using the
startTimeInMillis()function right before NewRelic starts in the
application(:didFinishLaunchingWithOptions:)method. This will ensure we are getting all of the load time counted, including the time it takes for New Relic to start. Typically, we want the New Relic Agent started as the very first item, but since this timer is itself instrumentation, we will go ahead and break this rule, just this once.
Stop the Timer
From there we navigate to our stopping point: the bottom of the
viewDidLoad()function of my initial view controller. Here we will grab a reference to the appDelegate and call the
stop()method to halt the stopwatch.
Retrieve the Launch Time
The value we want is now contained in our NRTimer object. To retrieve the time, we will call the
timeElapsedInMilliSeconds()function. Go ahead and take a look at this value in the console!
Use Your Data
Great! We have the number of milliseconds it has taken to start the application! Now we want to send this information to New Relic using the so I can use this valuable data in an Insights dashboard. This will be set as a custom attribute, within the MobileSession event. You can find out more on this method in the associated documentation!
And… that’s it! Toldja it was easy! Just start, stop and send!