Created
November 2, 2024 11:06
-
-
Save Mufanc/9cc8ce3416aff34b4526cd2ce4076c2c to your computer and use it in GitHub Desktop.
Get page cache statistics for files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdio> | |
#include <cstdint> | |
#include <fcntl.h> | |
#include <sys/mman.h> | |
#include <sys/stat.h> | |
#include <unistd.h> | |
int main(int argc, char *argv[]) { | |
if (argc == 1) { | |
fprintf(stderr, "usage: pcstat <file>"); | |
return 1; | |
} | |
printf("name:\t%s\n", argv[1]); | |
struct stat fs {}; | |
if (stat(argv[1], &fs) != 0) { | |
perror("error stat file"); | |
return 1; | |
} | |
size_t file_size = fs.st_size; | |
size_t page_size = getpagesize(); | |
printf("size:\t%zu\n", file_size); | |
size_t pages = (file_size + (page_size - 1)) / page_size; | |
printf("pages:\t%zu\n", pages); | |
int fd = open(argv[1], O_RDONLY); | |
if (fd == -1) { | |
perror("error open file"); | |
return 1; | |
} | |
void *base = mmap(nullptr, pages * page_size, PROT_READ, MAP_PRIVATE, fd, 0); | |
auto *ptr = new uint8_t[pages * page_size]; | |
mincore(base, pages * page_size, ptr); | |
size_t cached = 0; | |
for (size_t i = 0; i < pages; i++) { | |
if (ptr[i] & 1) { | |
cached++; | |
} | |
} | |
delete[] ptr; | |
printf("cached:\t%zu (%.2f%%)\n", cached, (float) cached / (float) pages * 100); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment