"is there any way to get the application's run time in cocoa for os x?" Code Answer


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]);
By Ken M. Haggerty on May 17 2022

Answers related to “is there any way to get the application's run time in cocoa for os x?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.