View Javadoc
1   /*
2    * Copyright 2020-2022 The OSHI Project Contributors
3    * SPDX-License-Identifier: MIT
4    */
5   package oshi.driver.unix.aix.perfstat;
6   
7   import com.sun.jna.platform.unix.aix.Perfstat;
8   import com.sun.jna.platform.unix.aix.Perfstat.perfstat_cpu_t;
9   import com.sun.jna.platform.unix.aix.Perfstat.perfstat_cpu_total_t;
10  import com.sun.jna.platform.unix.aix.Perfstat.perfstat_id_t;
11  
12  import oshi.annotation.concurrent.ThreadSafe;
13  
14  /**
15   * Utility to query performance stats for cpu
16   */
17  @ThreadSafe
18  public final class PerfstatCpu {
19  
20      private static final Perfstat PERF = Perfstat.INSTANCE;
21  
22      private PerfstatCpu() {
23      }
24  
25      /**
26       * Queries perfstat_cpu_total for total CPU usage statistics
27       *
28       * @return usage statistics
29       */
30      public static perfstat_cpu_total_t queryCpuTotal() {
31          perfstat_cpu_total_t cpu = new perfstat_cpu_total_t();
32          int ret = PERF.perfstat_cpu_total(null, cpu, cpu.size(), 1);
33          if (ret > 0) {
34              return cpu;
35          }
36          return new perfstat_cpu_total_t();
37      }
38  
39      /**
40       * Queries perfstat_cpu for per-CPU usage statistics
41       *
42       * @return an array of usage statistics
43       */
44      public static perfstat_cpu_t[] queryCpu() {
45          perfstat_cpu_t cpu = new perfstat_cpu_t();
46          // With null, null, ..., 0, returns total # of elements
47          int cputotal = PERF.perfstat_cpu(null, null, cpu.size(), 0);
48          if (cputotal > 0) {
49              perfstat_cpu_t[] statp = (perfstat_cpu_t[]) cpu.toArray(cputotal);
50              perfstat_id_t firstcpu = new perfstat_id_t(); // name is ""
51              int ret = PERF.perfstat_cpu(firstcpu, statp, cpu.size(), cputotal);
52              if (ret > 0) {
53                  return statp;
54              }
55          }
56          return new perfstat_cpu_t[0];
57      }
58  
59      /**
60       * Returns affinity mask from the number of CPU in the OS.
61       *
62       * @return affinity mask
63       */
64      public static long queryCpuAffinityMask() {
65          int cpus = queryCpuTotal().ncpus;
66          if (cpus < 63) {
67              return (1L << cpus) - 1;
68          }
69          return cpus == 63 ? Long.MAX_VALUE : -1L;
70      }
71  }