Execution time of one program

Hello! How can I measure the execution time of one program?

Hi! Not sure what you mean with execution time of one program, as Processing programs often stay running until you close them. This can be used to measure execution time of parts of your program:

  long t = System.currentTimeMillis();
  // do slow stuff
  println(System.currentTimeMillis() - t);

With this you can find out for how long the program has run until you press ESC:

void keyPressed() {
  if(key == ESC) {
    println(millis());
  }
}

Or did you have something else in mind?

2 Likes

Sorry! I just saw the reply, as far as I see this measure the global timing of the program, but is it possible to measure the timing since one “flag” is activated until is deactivated?

I think that’s the first example I posted:

  long t = System.currentTimeMillis(); // start "stopwatch"
  // ...
  // do slow stuff 
  // ...
  println(System.currentTimeMillis() - t); // stop "stopwatch"

Maybe you didn’t notice the - t part?

Yes. Here is an example of a randomly starting and stopping a simple timer and checking the result.

boolean flag;
int startTime;
int stopTime;

void setup(){
}

void draw(){
  float rand = random(1);
  println(rand);
  if(!flag && rand>0.99){
    flag = true;
    startTime = millis();
  }
  
  if(flag && rand<0.01){
    stopTime = millis();
    int result = stopTime - startTime;
    println("start", startTime, "stop", stopTime, "result", result);
    exit();
  }
}

and here is a simple example of setting a countdown duration and having it triggered:

boolean flag;
int startTime;
int duration;

void setup(){
  duration = 2000;
}

void draw(){
  float rand = random(1);
  println(rand);
  if(!flag && rand>0.99){
    flag = true;
    startTime = millis();
  }
  
  if(millis()-startTime > duration){
    int result = millis();
    println("start", startTime, "duration", duration, "stopTime", result);
    exit();
  }
}

…and if you need more timing functions, there are some great libraries full of features on the Libraries resource page:

https://processing.org/reference/libraries/

…in particular, Timing Utilities and Countdown Timer:

1 Like

I’ve got a raw “.java” pseudo-library here too called “Countdown Class”: :innocent:

1 Like

Thanks to all for yours answers! there were very helpful :grinning:

Hey, @GoToLoop – I feel like perhaps I have left yours out of a list several times. Have you ever considered making it a library and sharing it on the Libraries page for ease of finding?

You mean as an official Processing library? It’s so small I don’t think it’s worth it. :pensive: