Dave's Brain

Browse - programming tips - programmatically get load average

Date: 2009jun3
OS: Linux
Language: C/C++

Q.  How can I programatically get the load average?

A.  Read and parse the /proc/loadavg file.
Here's a C function:

bool loadavg(float *out)
{
	FILE	*f;
	float	avg;
	int	n;

	if (out == NULL) return false;
	*out = 0.0;
	if ((f = fopen("/proc/loadavg", "r")) == NULL) return false;
	n = fscanf(f, "%f", &avg);
	fclose(f);
	if (n != 1) return false;
	*out = avg;
	return true;
}

example_use()
{
	float	avg;

	if (!loadavg(&avg))
	{
		printf("Could not get load average\n");
		return;
	}

	printf("load=%f\n", avg);
}
What this info useful to you? You can donate to say thanks

Add a comment

Sign in to add a comment
Copyright © 2008-2012, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.
Advertisements: