Get the boot time in objective c

前端 未结 2 945
时光说笑
时光说笑 2020-12-30 18:59

how can i get the boot time of ios in objective c ?

Is there a way to get it?

2条回答
  •  不思量自难忘°
    2020-12-30 19:21

    I took JeremyP's answer, gave the result the full microsecond precision, clarified the names of local variables, improved the order, and put it into a method:

    #include 
    #include   
    
    // ....  
    
    + (nullable NSDate *)bootDate
    {
        // nameIntArray and nameIntArrayLen
        int nameIntArrayLen = 2;
        int nameIntArray[nameIntArrayLen];
        nameIntArray[0] = CTL_KERN;
        nameIntArray[1] = KERN_BOOTTIME;
    
        // boot_timeval
        struct timeval boot_timeval;
        size_t boot_timeval_size = sizeof(boot_timeval);
        if (sysctl(nameIntArray, nameIntArrayLen, &boot_timeval, &boot_timeval_size, NULL, 0) == -1)
        {
            return nil;
        }
    
        // bootSince1970TimeInterval
        NSTimeInterval bootSince1970TimeInterval = (NSTimeInterval)boot_timeval.tv_sec + ((NSTimeInterval)boot_timeval.tv_usec / 1000000);
    
        // return
        return [NSDate dateWithTimeIntervalSince1970:bootSince1970TimeInterval];
    }
    

提交回复
热议问题