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]);
}