Skip to content

Instantly share code, notes, and snippets.

@NSEGeorge
Last active November 25, 2019 10:06
Show Gist options
  • Save NSEGeorge/90ce6612b05bdf4e67802eb32e416090 to your computer and use it in GitHub Desktop.
Save NSEGeorge/90ce6612b05bdf4e67802eb32e416090 to your computer and use it in GitHub Desktop.
C function for measuring application launch time. Call it from start or end didFinishLaunchingWithOptions.
#include "LaunchTimeMeasurer.h"
#include <sys/sysctl.h>
#include <sys/unistd.h>
double processUptime() {
struct timeval currentTime; // current time returned by gettimeofday
struct kinfo_proc processInfo; // information about current process returned by sysctl
size_t processInfoSize = sizeof(processInfo); // information's size
int mib[] = { // Management Information Base
CTL_KERN, // "high kernel": proc, limits
KERN_PROC, // process entries
KERN_PROC_PID, // filter by id of process
getpid() // id of current process
};
/*
int sysctl (int *name, int nlen, void *oldval,
size_t *oldlenp, void *newval, size_t newlen);
* name points to an array of integers: each of the integer values identifies a sysctl item, either a directory or a leaf node file. The symbolic names for such values are defined in <linux/sysctl.h>.
* nlen states how many integer numbers are listed in the array name: to reach a particular entry you need to specify the path through the subdirectories, so you need to tell how long is such path.
* oldval is a pointer to a data buffer where the old value of the sysctl item must be stored. If it is NULL, the system call won't return values to user space.
* oldlenp points to an integer number stating the length of the oldval buffer. The system call changes the value to reflect how much data has been written, which can be less than the buffer length.
* newval points to a data buffer hosting replacement data: the kernel will read this buffer to change the sysctl entry being acted upon. If it is NULL, the kernel value is not changed.
* newlen is the length of newval. The kernel will read no more than newlen bytes from newval.
*/
sysctl(mib, sizeof(mib)/sizeof(int), &processInfo, &processInfoSize, NULL, 0);
gettimeofday(&currentTime, NULL);
return toSeconds(currentTime) - toSeconds(processInfo.kp_proc.p_starttime);
}
double toSeconds(struct timeval time) {
const int microsecondsInSecond = 1000000;
return time.tv_sec + (double)time.tv_usec / microsecondsInSecond;
}
@M0rtyMerr
Copy link

M0rtyMerr commented Oct 24, 2018

Such a perfect implementation, very useful, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment