How use millis() in static methods?

edited June 2016 in Library Questions

Hello, I want to calculate the time within the Serialevent Methode.

static class SerialPortReader implements SerialPortEventListener {

    public void serialEvent(SerialPortEvent event) {
        startLoop = millis(); 
        ...
        ...
        long endLoop = millis();                    
        println("Looptime = "+(endLoop - startLoop));

    }// End of serialEvent  
}// End of SerialPortReader 

I'm not static friendly :)) ;)

Answers

  • Answer ✓

    why are you using static classes?

    if you're only using it for timing, like above, then use new Date().getTime();

    otherwise, millis() is actually a method belonging to PApplet so you can pass that into your class and store it

    import java.util.Date;
    
    void setup() {
      A a = new A(this);
    }
    
    static class A {
      PApplet p;
      public A(PApplet p) {
        this.p = p;
      }
      public void usingPApplet() {
        long start = p.millis(); // milliseconds since start of program
        long end = p.millis(); // milliseconds since start of program
        long timeTaken = end - start;
      }
      public void usingDate() {
        long start = new Date().getTime(); // milliseconds since 1970
        long end = new Date().getTime(); // milliseconds since 1970
        long timeTaken = end - start;
      }
    }
    
    // non-static class can access methods from PApplet directly
    class B {
      public void usingMillis() {
        long start = millis(); // milliseconds since start of program
        long end = millis(); // milliseconds since start of program
        long timeTaken = end - start;
      }
    }
    
  • Thanks for the very quick response. ^:)^

    My serial communication is not fast enough. I want display the time within the Serialevent loop.

    I will try it.

  • actually, don't bother with Date, there are easier ways:

    System.currentTimeMillis()
    

    will give you the same information without having to create the date object.

    http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/System.html#currentTimeMillis()

    System.nanoTime()
    

    does the same thing with nanoseconds (but probably won't give you nanoseconds because your system won't report them. also, time might go backwards using this)

    http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/System.html#nanoTime()

  • edited June 2016

    I have tried it successfully.

    But i use static class no more. "why are you using static classes?" Thanks for your hint.

    The event loop time is OK. msec 1-4. But the problem isn't solved. The graphic is relatively slow.

Sign In or Register to comment.