详情请参考 iOS Application launch time on device
我们知道在调试的时候通过设置环境变量DYLD_PRINT_STATISTICS
可以在调试窗口输出main
函数前的耗时.
有没有办法通过API获取呢?以下就是方案之一
#include "LaunchTimeMeasurer.h"
#include <sys/sysctl.h>;
#include <sys/unistd.h>;
double processUptime() {
struct timeval currentTime; // 1
struct kinfo_proc processInfo // 2;
size_t processInfoSize = sizeof(processInfo) // 3;
int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()}; // 4
sysctl(mib, sizeof(mib)/sizeof(int), &processInfo, &processInfoSize, NULL, 0); // 5
gettimeofday(&currentTime, NULL); // 6
return toSeconds(currentTime) - toSeconds(processInfo.kp_proc.p_starttime); // 7
}
double toSeconds(struct timeval time) {
const int microsecondsInSecond = 1000000;
return time.tv_sec + (double)time.tv_usec / microsecondsInSecond;
}
- sysctl
- CTL_KERN — “high kernel”: proc, limits
- KERN_PROC — process entries
- KERN_PROC_PID — filter by id of process
- getpid() — id of current process
+ (BOOL)processInfoForPID:(int)pid procInfo:(struct kinfo_proc *)procInfo
{
int cmd[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid};
size_t size = sizeof(*procInfo);
return sysctl(cmd, sizeof(cmd) / sizeof(*cmd), procInfo, &size, NULL, 0) == 0;
}
+ (NSTimeInterval)processStartTime
{
struct kinfo_proc kProcInfo;
if ([self processInfoForPID:getpid() procInfo:&kProcInfo]) {
return kProcInfo.kp_proc.p_un.__p_starttime.tv_sec + kProcInfo.kp_proc.p_un.__p_starttime.tv_usec / 1000000.0;
} else {
NSAssert(NO, @"无法取得进程的信息");
return 0;
}
}
网友评论