I am trying to calculate number of page faults while reading a file of size 1kB to 1GB using C program on Linux. I am using below mentioned steps:
- I created a dummy file using
dd if=/dev/zero of=file1.txt count=1024 bs=1024
- I flushed the pagecache using
# sync; echo 1 > /proc/sys/vm/drop_caches
- I wrote a c program using getrusage() to calculate the number of page fault
#include <sys/time.h> #include <sys/resource.h> #include <unistd.h> #include <stdio.h> int main() { struct rusage usage; //struct timeval start, end; long int st,ed; int i, j, k = 0; getrusage(RUSAGE_SELF, &usage); st = usage.ru_majflt; FILE *fp; int c; int n = 0; fp = fopen("file6.txt","r"); if(fp == NULL) { perror("Error in opening file"); return(-1); } while(!feof(fp)) { c = fgetc(fp); } fclose(fp); getrusage(RUSAGE_SELF, &usage); ed = usage.ru_majflt; printf("Started at: %ld \n", st); printf("Ended at: %ld \n", ed); return 0; }
When I ran the code I got an unexpected output.
Started at: 0
Ended at: 0
Where I went wrong?