有没有办法在Cocoa for OS X中获取应用程序的运行时间?

And*_*ang 3 macos cocoa systemtime

我想在我的应用程序中按时运行.我首先考虑的是系统uptime.由于这看起来很难实现,我很好奇是否有一种简单有效的方法来获取应用程序的运行时间?

以毫秒或时间间隔更好的时间.

Tho*_*ing 5

获得应用程序运行时间近似值的最简单方法applicationDidFinishLaunching:是在调用app delegate方法时存储NSDate,并在需要进程运行时间时从当前时间减去该日期.

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

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

如果您需要更准确的PID运行间隔,您可以使用sysctl.
这将为您提供操作系统认为您的进程在UNIX时间"运行"的点的确切时间戳.(如果您希望在本地时区中添加时间戳,可以使用NSDateFormatter如下所示).

#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]);
}
Run Code Online (Sandbox Code Playgroud)