Monitor the speed of my Code

Hello all,

is there an internal variable like width which tells us

how many Code Lines were worked through

during the last frame?

That would help to monitor the efficiency of

some parts of the Sketch in a simple way. (Proposal).

Thanks and warm regards!

Chrisir

I am assuming you are referring to Java mode :slightly_smiling_face:

An interesting idea but realistically a code line count would not be a measure of efficiency, especially when a code line can have multiple statements.

In programming the most common metrics for measuring efficiency are

  • execution type and
  • memory usage

You have to be careful when measuring elapsed time because the JRE performs runtime optimization on code that is visited / executed a lot, leading to improved speed as the program runs.

This example displays the average time to execute the statements in the draw method. It measures in milliseconds (10-3s) and nanoseconds(10-9s).

NOTE: The resolution of the value returned by System.nanoTime() depends on your computer hardware, you can find out more here.

long mt = 0, nt = 0, cnt = 0;
int s = 20;  // color tile size

void setup() {
  size(640, 480);
  stroke(0);
  strokeWeight(0.75);
  colorMode(HSB, 360, 100, 100);
  textSize(16);
}

void draw() {
  long mte = System.currentTimeMillis();
  long nte = System.nanoTime();
  cnt++;
  background(248);
  for (int y = 60; y < height; y += s) {
    for (int x = 0; x < width; x += s) {
      fill(randomColor());
      rect(x, y, s, s);
    }
  }

  // Keep a running sum for execution times
  mt += System.currentTimeMillis() - mte;
  nt += System.nanoTime() - nte;
  // Do not include the following code in calculating time metrics.
  calcAndDisplayTimeMetrics(nt, mt, cnt);
}

// This function calculates and displays the average execution time
// but is not included in the time metric
void calcAndDisplayTimeMetrics(long nt, long mt, long cnt) {
  int w2 = width /2;
  fill(0);
  textAlign(CENTER);
  text("Average Execution Time", 0, 0, width, 20);
  textAlign(LEFT);
  text("milliseconds", w2, 20, w2, 20);
  text("nanoseconds", w2, 40, w2, 20);
  textAlign(RIGHT);
  text(""+round(mt/cnt), 0, 20, w2 - 10, 20);
  text(""+round(nt/cnt), 0, 40, w2 - 10, 20);
}

int randomColor() {
  return color(floor(random(360)), int(random(25, 100)), int(random(50, 100)));
}

Display using a tile size of 20 pixels, you can try other sizes to see what happens :grin:

JavaScript has the statements

console.time()
console.timeLog()
console.timeEnd()

to measure execution times. If I have never used them but if I understand correctly they can easily be used to measure and report execution times for different parts of the same program but only in millisecond resolution. Might be interesting to create something that does the same but for Java, I might investigate that if anyone is interested.