Calculating elapsed microseconds

Hi there!

I am measuring the elapsed time of a code in a for-loop in draw():

void draw(){
  for(byte i = 0; i < 10; i++){
    time_prev = millis();
    
    //code
    
    time_now = millis();
    deltaT = time_now - time_prev;
  }
}

The problem is that the elapsed time in a for-loop is smaller than 1 ms, so deltaT is equal to 0 each time… Is there any way to measure the elapsed time in microseconds?

Thanks in advance,

MrImskiy

You might try this

void setup() {
  size(400, 400);
  frameRate(5);
}

void draw() {
  background(128);
  stroke(0);
  strokeWeight(1.5);
  int r = (int)random(160, 255);
  int g = (int)random(160, 255);
  int b = (int)random(160, 255);
  fill(color(r, g, b));

  long time = System.nanoTime();
  ellipse(random(100, 300), random(100, 300), random(50, 300), random(50, 300));
  time = System.nanoTime() - time;

  println(time+ " nanoseconds       " + time/1000 + " microseconds");
}

There are some things you should be aware of when using System.nanoTime() read here

3 Likes

Thanks @quark ! :slight_smile: That seems to do the job!

1 Like