我想在我的应用程序中进行长时间操作.我首先考虑的是系统的uptime.由于这看起来很难实现,我很好奇是否有一种简单有效的方法来获取应用程序的运行时间?
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.
推荐答案最接近应用程序运行时间的最简单方法是在调用应用程序委托方法applicationDidFinishLaunching:时存储NSDate并从中减去该日期需要流程运行时间的当前时间.
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); }如果需要更精确的PID运行间隔,则可以使用sysctl. 这将为您提供确切的时间戳,以表明操作系统认为您的进程在UNIX时间中正在运行". (如果要在本地时区中使用时间戳记,则可以使用如下所示的NSDateFormatter.)
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]); }更多推荐
有什么方法可以在OS X的Cocoa中获取应用程序的运行时间吗?
发布评论