How to make sampling frequency constant?

// MPU-6050 Short Example Sketch
// By Arduino User JohnChi
// August 17, 2014
// Public Domain
#include<Wire.h>
  const int MPU=0x68;  // I2C address of the MPU-6050
  int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;
  unsigned long startmilli,endmilli,dur;
void setup(){
  Wire.begin();
  //Wire.setClock(400000L)
  Wire.beginTransmission(MPU);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
  Serial.begin(9600);
 startmilli=millis();
}
void loop(){
  Wire.beginTransmission(MPU);
  Wire.write(0x47);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU,2,true);  // request a total of 14 registers
  GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
  endmilli=millis();
  dur=(endmilli-startmilli);
  startmilli=endmilli;
  Serial.println(dur);  
}

I am using this to read z- gyroscope register of MPU6050. This takes 3 or 4 milliseconds to execute 1 loop. So depending on that sampling frequency changes from 333.33Hz to 250 Hz. But I want A constant sampling frequency.
Is there any timer function so that I will call the function to read gyro readings after every 5 milliseconds?
Is my way of calculating sampling frequency correct? (I know this is not the true sampling frequency, But
this is the rate I am getting sensor output.)

Read up on how to use millis().

E.g. Using millis() for timing. A beginners guide
and Demonstration code for several things at the same time

Define a constant called samplePeriod at the top of your code. Give it the milliseconds you want, like 5.

Then call this function anywhere in loop():

void delaySamplePeriod() {
  static unsigned long lastTime = 0;
  if (millis() - lastTime > samplePeriod) {
    Serial.println("1202 alarm");
    lastTime = millis();
  } else {
    while (millis() - lastTime < samplePeriod) {
      //wait
      yield();
    }
    lastTime += samplePeriod;
  }
}

yield() is rarely seen in Arduino code. It allows some Arduinos like the Due and Teensy to do other tasks. On every other type of Arduino, it does nothing.

You should get used to using local variables. Everything in your code is global. As your programs get larger, it's difficult to keep track of which function has "control" of the endmilli variable. If you make it a static variable inside a function then no other function can mess with this and you can have an unlimited number of endmilli used anywhere in your code.

MorganS the code is working fine. Thanks a lot. But I am not getting why after 1000 seconds it is showing "1202 alarm" frequently.

The problem is in the code you didn't post.