Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

请问能获取到CPU分别在 1min, 5min, 15min内的CPU使用情况吗? #7

Closed
zhihuitang opened this issue Oct 10, 2017 · 4 comments
Assignees

Comments

@zhihuitang
Copy link

No description provided.

@aozhimin
Copy link
Owner

@zhihuitang 没太清楚这个问题的意思,起一个子线程每隔一秒钟就抓一次 CPU 使用情况,这样再看 1min, 5min, 15min内的CPU使用情况,能满足你这个需求吗?

@aozhimin aozhimin self-assigned this Oct 10, 2017
@zhihuitang
Copy link
Author

@aozhimin 谢谢,在Swift中已经找到方法了, 就是获得uptime后面的CPU占用率(1min, 5min, 15min)

func getCPULoadAvg() -> [Double]{
        var loadAvg = [Double](repeating: 0, count: 3)
        getloadavg(&loadAvg, 3)
        return loadAvg
    }

@zhihuitang
Copy link
Author

在Objective-C中是这样的:

typedef struct {
    double m1;
    double m5;
    double m15;
} Upclodavg;


+ (Upclodavg)lodavg {
    double loadavg[3];
    getloadavg(loadavg, 3);
    Upclodavg cpuLoadAvg = {0,0,0};
    
    // 1 mins
    cpuLoadAvg.m1 = loadavg[0];
    
    // 5 mins
    cpuLoadAvg.m5 = loadavg[1];
    
    // 15 mins
    cpuLoadAvg.m15 = loadavg[2];
    return cpuLoadAvg;
}

@aozhimin
Copy link
Owner

@zhihuitang 好的,明白了,
Libc 的 getloadavg

/*
 * getloadavg() -- Get system load averages.
 *
 * Put `nelem' samples into `loadavg' array.
 * Return number of samples retrieved, or -1 on error.
 */
int
getloadavg(loadavg, nelem)
	double loadavg[];
	int nelem;
{
	struct loadavg loadinfo;
	int i, mib[2];
	size_t size;

	mib[0] = CTL_VM;
	mib[1] = VM_LOADAVG;
	size = sizeof(loadinfo);
	if (sysctl(mib, 2, &loadinfo, &size, NULL, 0) < 0)
		return (-1);

	nelem = MIN(nelem, sizeof(loadinfo.ldavg) / sizeof(fixpt_t));
	for (i = 0; i < nelem; i++)
		loadavg[i] = (double) loadinfo.ldavg[i] / loadinfo.fscale;
	return (nelem);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants