[go: up one dir, main page]

File: load_average.c

package info (click to toggle)
cctools 9.9-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 44,624 kB
  • sloc: ansic: 192,539; python: 20,827; cpp: 20,199; sh: 11,719; perl: 4,106; xml: 3,688; makefile: 1,224
file content (92 lines) | stat: -rw-r--r-- 1,593 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/*
Copyright (C) 2008- The University of Notre Dame
This software is distributed under the GNU General Public License.
See the file COPYING for details.
*/

#if defined(CCTOOLS_OPSYS_DARWIN)

#include <unistd.h>
#include <stdlib.h>
#include <sys/sysctl.h>
#include <sys/types.h>

void load_average_get(double *avg)
{
	avg[0] = avg[1] = avg[2] = 0;
	getloadavg(avg, 3);
}

int load_average_get_cpus()
{
	int n;
	size_t size = sizeof(n);
	if(sysctlbyname("hw.physicalcpu", &n, &size, 0, 0) == 0) {
		return n;
	} else {
		return 1;
	}
}

#elif defined(CCTOOLS_OPSYS_LINUX)

#include <stdio.h>
#include <stdlib.h>

#include "stringtools.h"
#include "string_set.h"

void load_average_get(double *avg)
{
	FILE *f;
	avg[0] = avg[1] = avg[2] = 0;
	f = fopen("/proc/loadavg", "r");
	if(f) {
		fscanf(f, "%lf %lf %lf", &avg[0], &avg[1], &avg[2]);
		fclose(f);
	}
}

int load_average_get_cpus()
{
	struct string_set *cores;
	cores = string_set_create(0, 0);

	for (int i = 0; ; i++) {
		char *p = string_format("/sys/devices/system/cpu/cpu%u/topology/thread_siblings", i);
		FILE *f = fopen(p, "r");
		free(p);
		if (!f) break;

		char line[1024];
		int rc = fscanf(f, "%1023s", line);
		fclose(f);
		if (rc != 1) break;

		string_set_push(cores, line);
	}

	int cpus = string_set_size(cores);
	string_set_delete(cores);
	if (cpus < 1) {
		cpus = 1;
		fprintf(stderr, "Unable to detect CPUs, falling back to 1\n");
	}
	return cpus;
}

#else

void load_average_get(double *avg)
{
	avg[0] = avg[1] = avg[2] = 0;
}

int load_average_get_cpus()
{
	return 1;
}

#endif

/* vim: set noexpandtab tabstop=4: */