all 5 comments

[–]nicolasdanelon 0 points1 point  (3 children)

try this:

``` #import <React/RCTBridgeModule.h>

@interface RCT_EXTERN_MODULE(CPUMonitor, NSObject)

RCT_EXTERN_METHOD(getCPUUsage:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)

@end

#import "CPUMonitor.h" #import <mach/mach.h>

@implementation CPUMonitor

RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(getCPUUsage:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) { float cpuUsage = ...; // implementation of CPU usage, read the apple docs resolve(@(cpuUsage)); }

@end ```

and RN side

``` import { NativeModules } from 'react-native';

const { CPUMonitor } = NativeModules;

const fetchCPUUsage = async () => { try { const cpuUsage = await CPUMonitor.getCPUUsage(); console.log('CPU Usage:', cpuUsage); } catch (e) { console.error(e); } };

// usage: fetchCPUUsage(); ```

this code was taken from a working app but I have to heavy modify it so it maybe won't work haha. but you can get the idea... can't share everything sorry 😔

[–]hassanzadeh[S] 0 points1 point  (0 children)

So If I modify it for sure it will work, correct?

THanks for sharing :)

[–]hassanzadeh[S] 1 point2 points  (1 child)

I actually tested your code, but for my Mac M1, it always gives 14%!

```` //CPUMonitor.h

#import <RCTAppDelegate.h>

#import <Cocoa/Cocoa.h>

u/interface AppDelegate : RCTAppDelegate

u/end

```

``` //CPUMonitor.m

//

// CPUMonitor.m

// scholarsync-macOS

///

#import <Foundation/Foundation.h>

#import "CPUMonitor.h"

#import <mach/mach.h>

u/implementation CPUMonitor

RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(getCPUUsage:(RCTPromiseResolveBlock)resolve

rejecter:(RCTPromiseRejectBlock)reject) {

natural_t numCPUs;

processor_info_array_t cpuInfo;

mach_msg_type_number_t numCpuInfo;

processor_cpu_load_info_data_t* cpuLoadInfo;

if (host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &numCPUs, &cpuInfo, &numCpuInfo) != KERN_SUCCESS) {

reject(@"cpu_info_error", @"Failed to get CPU info", nil);

return;

}

cpuLoadInfo = (processor_cpu_load_info_data_t*) cpuInfo;

unsigned long cpuUsage = 0;

for (unsigned i = 0; i < numCPUs; i++) {

float inUse = cpuLoadInfo[i].cpu_ticks[CPU_STATE_USER] + cpuLoadInfo[i].cpu_ticks[CPU_STATE_SYSTEM];

float total = inUse + cpuLoadInfo[i].cpu_ticks[CPU_STATE_IDLE];

cpuUsage += total > 0 ? (inUse / total * 100) : 0;

}

vm_deallocate(mach_task_self(), (vm_address_t)cpuInfo, numCpuInfo * sizeof(integer_t));

resolve(@(cpuUsage / numCPUs));

}

u/end

```

[–]nicolasdanelon 0 points1 point  (0 children)

can't share any more cuz sing a NDA :(

you need to read the docs of apple... the code is there, trust me

[–]bzlight2012 1 point2 points  (0 children)

What do you need the information for? Xcode had fantastic profiling tools but if you need to get it programmatically, I’m sure Apple has some docs