2

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?

  • 4
    Why do you expect page faults? Your code does not consume memory. – rici Jan 30 '18 at 08:13
  • In your file loop you just keep overwriting `c`. You are only using `sizeof(int)`, it is not reading the whole file into memory. Also, page faults will vary depending on overall system memory consumption, i.e. other processes. – cdarke Jan 30 '18 at 08:21
  • @rici can you write in answer how to bring complete file in buffer that would lead to page fault. I tried the same with fread() but still getting 0. – Akhilesh Yadav Jan 30 '18 at 09:16
  • @cdarke any I idea how to calculate page fault only due to this operation? – Akhilesh Yadav Jan 30 '18 at 09:21
  • @AkhileshYadav: on an empty machine it might load the whole lot into RAM and never have a page fault. The number of page faults is not a constant for one particular program. Try running multiple copies (hundreds) of the program at the same time, and slow them down a bit with some CPU activity. – cdarke Jan 30 '18 at 14:01

0 Answers0