有什么方法可以在OS X的Cocoa中获取应用程序的运行时间吗?

编程入门 行业动态 更新时间:2024-10-24 18:17:23
本文介绍了有什么方法可以在OS X的Cocoa中获取应用程序的运行时间吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想在我的应用程序中进行长时间操作.我首先考虑的是系统的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中获取应用程序的运行时间吗?

本文发布于:2023-10-07 14:54:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1469693.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有什么   应用程序   时间   方法   OS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!