Search code examples
clinuxnvidia-jetson-nano

Jetson Nano Temperature C


I have a couple of questions on this piece of code, running on a jetson nano:

#include "stdio.h"
#include "unistd.h"
#include "stdlib.h"

float gputemp = 0;
float cputemp = 0;
int count = 0;

int main() {
    char* cpu;
    char* gpu;
    cpu = (char*)malloc(sizeof(char)*6);
    gpu = (char*)malloc(sizeof(char)*6);
    

    while (1) {
        FILE* fcputemp = fopen("/sys/devices/virtual/thermal/thermal_zone1/temp", "r");
        FILE* fgputemp = fopen("/sys/devices/virtual/thermal/thermal_zone2/temp","r");
        if (!fcputemp || !fgputemp ) {
            printf("Something went wrong\n");
            exit(EXIT_FAILURE);
        }
        
        cputemp = atoi(fgets(cpu, 6, fcputemp))/1000;
        gputemp = atoi(fgets(gpu, 6, fgputemp))/1000;
        
        printf("\rCpu : %.2f, Gpu : %.2f. Elapsed time : %d", cputemp, gputemp, count);
        fflush(stdout);
        
        fclose(fcputemp);
        fclose(fgputemp);
        
        count++;
        sleep(1);
    }
}

Here I have to open, get the temperatures, and then close the file each loop iteration in order to get valid data (and dont segfault). My concern here is the number of (expensive) kernel switches needed to do this.

I know that premature optimization is evil, but there is another way (or maybe the RIGHT way) to do that, opening the file only once?

And why the sensor interface (the file) cant update itself if I have it open?

P.S: Yes, I know, I didnt free cpu nor gpu variables, this is only "demo" code (just watch how i measure the time passed lol)


Solution

  • I'm not sure you can do this opening the files once and once only. You could try rewinding, but sysfs isn't a "real" filesystem and those aren't real files. If you rewind you might get the same data over and over, especially when using buffered calls like fopen().

    The open operation is what prepares that data for reading. Since this is all managed by the kernel it should have very little overhead, and no actual disk activity. Consider that programs like top read thousands of these every second and it's no big deal.