3

I want to operate with time in my app. What I considered first is system's uptime. Since that looked hard to achieve, I am curious that whether there is a simple and efficient way to get my application's run time?

Better time in miliseconds or timeinterval.

Thomas Zoechling
  • 34,177
  • 3
  • 81
  • 112
Andrew Chang
  • 1,289
  • 1
  • 18
  • 38

1 Answers1

6

The easiest way to get an approximation of your application's running time would be to store a NSDate when the app delegate method applicationDidFinishLaunching: is called and subtract that date from the current time whenever you need the process running time.

static NSTimeInterval startTime;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    startTime = [NSDate timeIntervalSinceReferenceDate];
}

- (IBAction)printRunningTime:(id)sender
{
    NSLog(@"Approximate running interval:%f", [NSDate timeIntervalSinceReferenceDate] - startTime);
}

If you need a more accurate running interval for your PID, you can use sysctl.
This will give you an exact timestamp for the point where the OS considers your process "running" in UNIX time. (If you want the timestamp in your local timezone, you can use a NSDateFormatter as below).

#include <sys/sysctl.h>
#include <sys/types.h>

- (IBAction)printRunningTime:(id)sender
{
    pid_t pid = [[NSProcessInfo processInfo] processIdentifier];
    int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
    struct kinfo_proc proc;
    size_t size = sizeof(proc);
    sysctl(mib, 4, &proc, &size, NULL, 0);

    NSDate* startTime = [NSDate dateWithTimeIntervalSince1970:proc.kp_proc.p_starttime.tv_sec];
    NSLog(@"Process start time for PID:%d in UNIX time %@", pid, startTime);

    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    [dateFormatter setTimeStyle:NSDateFormatterLongStyle];
    [dateFormatter setLocale:[NSLocale currentLocale]];
    NSLog(@"Process start time for PID:%d in local time %@", pid, [dateFormatter stringFromDate:startTime]);
}
Thomas Zoechling
  • 34,177
  • 3
  • 81
  • 112
  • However, if user changes the system time during my application's run time, may this solution cause error? – Andrew Chang Jul 05 '13 at 09:01
  • The first (simple) solution will result in a wrong time interval (as the initial time is incomparable to the modified system time). The second solution returns an absolute NSDate object. You could listen for the NSSystemClockDidChangeNotification notification and re-calculate the time interval accordingly. – Thomas Zoechling Jul 05 '13 at 09:50
  • Oh, that sounds feasible. Thank you!! – Andrew Chang Jul 05 '13 at 11:46