sourcecode

C를 사용하여 Linux에서 CPU 수를 얻는 방법

copyscript 2022. 8. 1. 22:41
반응형

C를 사용하여 Linux에서 CPU 수를 얻는 방법

Linux에서 사용할 수 있는 CPU의 수를 얻을 수 있는 API가 있나요?제 말은 /proc/cpuinfo나 다른 sys-node 파일을 사용하지 않으면...

이 실장은 스케치를 사용한 것입니다.h:

int GetCPUCount()
{
 cpu_set_t cs;
 CPU_ZERO(&cs);
 sched_getaffinity(0, sizeof(cs), &cs);

 int count = 0;
 for (int i = 0; i < 8; i++)
 {
  if (CPU_ISSET(i, &cs))
   count++;
 }
 return count;
}

하지만 일반 도서관을 이용하는 것보다 더 높은 수준은 없나요?

#include <stdio.h>
#include <sys/sysinfo.h>

int main(int argc, char *argv[])
{
    printf("This system has %d processors configured and "
        "%d processors available.\n",
        get_nprocs_conf(), get_nprocs());
    return 0;
}

https://linux.die.net/man/3/get_nprocs

#include <unistd.h>
long number_of_processors = sysconf(_SC_NPROCESSORS_ONLN);

최근 인텔 CPU에서는 다음과 같이 사용하고 있습니다.

int main()
{
unsigned int eax=11,ebx=0,ecx=1,edx=0;

asm volatile("cpuid"
        : "=a" (eax),
          "=b" (ebx),
          "=c" (ecx),
          "=d" (edx)
        : "0" (eax), "2" (ecx)
        : );
            
printf("Cores: %d\nThreads: %d\nActual thread: %d\n",eax,ebx,edx);
}

출력:

Cores: 4
Threads: 8
Actual thread: 1

또는 보다 간결하게 말하면:

#include <stdio.h>

int main()
{
unsigned int ncores=0,nthreads=0,ht=0;

asm volatile("cpuid": "=a" (ncores), "=b" (nthreads) : "a" (0xb), "c" (0x1) : );

ht=(ncores!=nthreads);

printf("Cores: %d\nThreads: %d\nHyperThreading: %s\n",ncores,nthreads,ht?"Yes":"No");

return 0;
}

출력:

Cores: 4
Threads: 8
HyperThreading: Yes

관련된 답변은 없습니다.sysconf(...)또는get_nprocs()는 CPU 어피니티에 의해 태스크로 제한된 프로세서의 수를 수용하는 데 적합합니다.

작업에 사용할 수 있는 프로세서의 수를 얻으려면 다음과 같은 것이 필요합니다.

#define _GNU_SOURCE
#include <sched.h>
#include <stdio.h>

int nprocs()
{
  cpu_set_t cs;
  CPU_ZERO(&cs);
  sched_getaffinity(0, sizeof(cs), &cs);
  return CPU_COUNT(&cs);
}

int main()
{
  printf("procs=%d\n", nprocs());
  return 0;
}

이 코드(여기서 작성)는 Windows 플랫폼과 *NIX 플랫폼 모두에서 작동합니다.

#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#else
#include <unistd.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>


int main() {
  long nprocs = -1;
  long nprocs_max = -1;
#ifdef _WIN32
#ifndef _SC_NPROCESSORS_ONLN
SYSTEM_INFO info;
GetSystemInfo(&info);
#define sysconf(a) info.dwNumberOfProcessors
#define _SC_NPROCESSORS_ONLN
#endif
#endif
#ifdef _SC_NPROCESSORS_ONLN
  nprocs = sysconf(_SC_NPROCESSORS_ONLN);
  if (nprocs < 1)
  {
    fprintf(stderr, "Could not determine number of CPUs online:\n%s\n", 
strerror (errno));
    exit (EXIT_FAILURE);
  }
  nprocs_max = sysconf(_SC_NPROCESSORS_CONF);
  if (nprocs_max < 1)
  {
    fprintf(stderr, "Could not determine number of CPUs configured:\n%s\n", 
strerror (errno));
    exit (EXIT_FAILURE);
  }
  printf ("%ld of %ld processors online\n",nprocs, nprocs_max);
  exit (EXIT_SUCCESS);
#else
  fprintf(stderr, "Could not determine number of CPUs");
  exit (EXIT_FAILURE);
#endif
}

sched_affinity()처음에 말씀하신 버전이 더 낫습니다./proc/cpuinfo및/또는_SC_NPROCESSORS_ONLN특정 프로세스에서 사용 가능한 CPU만 카운트하기 때문입니다(일부는 에 의해 비활성화될 수 있습니다).sched_setaffinity()외부 프로세스에 의해 호출됩니다).유일한 변경은 를 사용하는 것입니다.CPU_COUNT()하는 대신에CPU_ISSET고리를 틀어서.

사용./proc/cpuinfo가장 깨끗하고 휴대성이 뛰어난 솔루션입니다.오픈에 실패했을 경우는, 1 cpu 또는 2 cpu 를 상정할 수 있습니다.마이크로 최적화 이외의 목적(예를 들어 실행할 이상적인 스레드 수 선택)을 위해 CPU의 수를 아는 것에 의존하는 코드는 거의 확실히 바보 같은 일을 하고 있습니다.

_SC_NPROCESSORS_ONLN솔루션은 비표준(glibc 고유)에 의존합니다.sysconf확장기능이 확장기능에 비해 훨씬 더 큰 의존관계입니다./proc(모든 Linux 시스템에는/proc단, glibc 이외의 libc 또는 이전 버전의 glibc가 없는 것도 있습니다._SC_NPROCESSORS_ONLN).

sys 파일시스템에서 cpu* 디렉토리를 스캔하는 다른 방법:

#include<stdio.h>
#include <dirent.h>
#include <errno.h>
#define LINUX_SYS_CPU_DIRECTORY "/sys/devices/system/cpu"

int main() {
   int cpu_count = 0;
   DIR *sys_cpu_dir = opendir(LINUX_SYS_CPU_DIRECTORY);
   if (sys_cpu_dir == NULL) {
       int err = errno;
       printf("Cannot open %s directory, error (%d).\n", LINUX_SYS_CPU_DIRECTORY, strerror(err));
       return -1;
   }
   const struct dirent *cpu_dir;
   while((cpu_dir = readdir(sys_cpu_dir)) != NULL) {
       if (fnmatch("cpu[0-9]*", cpu_dir->d_name, 0) != 0)
       {
          /* Skip the file which does not represent a CPU */
          continue;
       }
       cpu_count++;
   }
   printf("CPU count: %d\n", cpu_count);
   return 0;
}

언급URL : https://stackoverflow.com/questions/4586405/how-to-get-the-number-of-cpus-in-linux-using-c

반응형