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

时间:2013-07-05 07:31:13

标签: macos cocoa systemtime

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

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

1 个答案:

答案 0 :(得分:5)

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

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

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

如果您需要更准确的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]);
}