C/C++ 프로그램 안에서 캐시 크기(라인 단위)를 알아낼 수 있을까요?

조회수 2163회

C/C++ 프로그램 안에서 캐시 크기(라인 단위)를 알아내는 코드를 알려주세요.

제 컴퓨터는 리눅스를 쓰고 있고 다른 플랫폼 코드도 알려주시면 고맙겠습니다.

모든 플랫폼에서 쓸 수 있는 코드면 좋겠지만 무리겠죠..?

1 답변

  • 좋아요

    0

    싫어요
    채택 취소하기

    GitHub - CacheLineSize에서 갖고 온 코드입니다.(멀티플랫폼에서 쓸 수 있음)

    #ifndef GET_CACHE_LINE_SIZE_H_INCLUDED
    #define GET_CACHE_LINE_SIZE_H_INCLUDED
    
    // Author: Nick Strupat
    // Date: October 29, 2010
    // Returns the cache line size (in bytes) of the processor, or 0 on failure
    
    #include <stddef.h>
    size_t cache_line_size();
    
    #if defined(__APPLE__)
    
    #include <sys/sysctl.h>
    size_t cache_line_size() {
        size_t line_size = 0;
        size_t sizeof_line_size = sizeof(line_size);
        sysctlbyname("hw.cachelinesize", &line_size, &sizeof_line_size, 0, 0);
        return line_size;
    }
    
    #elif defined(_WIN32)
    
    #include <stdlib.h>
    #include <windows.h>
    size_t cache_line_size() {
        size_t line_size = 0;
        DWORD buffer_size = 0;
        DWORD i = 0;
        SYSTEM_LOGICAL_PROCESSOR_INFORMATION * buffer = 0;
    
        GetLogicalProcessorInformation(0, &buffer_size);
        buffer = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION *)malloc(buffer_size);
        GetLogicalProcessorInformation(&buffer[0], &buffer_size);
    
        for (i = 0; i != buffer_size / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); ++i) {
            if (buffer[i].Relationship == RelationCache && buffer[i].Cache.Level == 1) {
                line_size = buffer[i].Cache.LineSize;
                break;
            }
        }
    
        free(buffer);
        return line_size;
    }
    
    #elif defined(linux)
    
    #include <stdio.h>
    size_t cache_line_size() {
        FILE * p = 0;
        p = fopen("/sys/devices/system/cpu/cpu0/cache/index0/coherency_line_size", "r");
        unsigned int i = 0;
        if (p) {
            fscanf(p, "%d", &i);
            fclose(p);
        }
        return i;
    }
    
    #else
    #error Unrecognized platform
    #endif
    
    #endif
    

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)