A 3D game engine from scratch.
1// Author: Nick Strupat
2// Date: October 29, 2010
3// Returns the cache line size (in bytes) of the processor, or 0 on failure
4
5#ifndef CACHELINE_H
6#define CACHELINE_H
7
8#include <stddef.h>
9size_t cacheline_get_size();
10
11#if defined(__APPLE__)
12
13#include <sys/sysctl.h>
14size_t cacheline_get_size() {
15 size_t line_size = 0;
16 size_t sizeof_line_size = sizeof(line_size);
17 sysctlbyname("hw.cachelinesize", &line_size, &sizeof_line_size, 0, 0);
18 return line_size;
19}
20
21#elif defined(_WIN32)
22
23#include <stdlib.h>
24#include <windows.h>
25size_t cacheline_get_size() {
26 size_t line_size = 0;
27 DWORD buffer_size = 0;
28 DWORD i = 0;
29 SYSTEM_LOGICAL_PROCESSOR_INFORMATION * buffer = 0;
30
31 GetLogicalProcessorInformation(0, &buffer_size);
32 buffer = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION *)malloc(buffer_size);
33 GetLogicalProcessorInformation(&buffer[0], &buffer_size);
34
35 for (i = 0; i != buffer_size / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); ++i) {
36 if (buffer[i].Relationship == RelationCache && buffer[i].Cache.Level == 1) {
37 line_size = buffer[i].Cache.LineSize;
38 break;
39 }
40 }
41
42 free(buffer);
43 return line_size;
44}
45
46#elif defined(linux)
47
48#include <stdio.h>
49size_t cacheline_get_size() {
50 FILE * p = 0;
51 p = fopen("/sys/devices/system/cpu/cpu0/cache/index0/coherency_line_size", "r");
52 unsigned int i = 0;
53 if (p) {
54 fscanf(p, "%d", &i);
55 fclose(p);
56 }
57 return i;
58}
59
60#else
61#error Unrecognized platform
62#endif
63
64#endif