以编程方式获取缓存行大小?
欢迎所有平台,请为您的答案指定平台。
一个类似的问题:如何以编程方式获取C ++中的CPU缓存页面大小?
在Linux上(具有合理的最新内核),您可以从/ sys中获取这些信息:
/sys/devices/system/cpu/cpu0/cache/
该目录具有每个缓存级别的子目录。 这些目录中的每一个都包含以下文件:
coherency_line_size
level
number_of_sets
physical_line_partition
shared_cpu_list
shared_cpu_map
size
type
ways_of_associativity
这为您提供了有关缓存的更多信息,包括缓存行大小以及哪些CPU共享此缓存。 如果您使用共享数据进行多线程编程(如果共享数据的线程也共享缓存,则会获得更好的结果),这非常有用。
在Linux上查看sysconf(3)。
sysconf (_SC_LEVEL1_DCACHE_LINESIZE)
你也可以使用getconf从命令行获得它:
$ getconf LEVEL1_DCACHE_LINESIZE
64
我一直在研究一些缓存行的东西,需要编写一个跨平台的函数。 我在https://github.com/NickStrupat/CacheLineSize将其提交给github repo,或者您可以使用下面的源代码。 随意做任何你想要的东西。
#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
                        链接地址: http://www.djcxy.com/p/13895.html
                        
                        
                    