Skip to content

Performance too slow for control feedback for a moving robot #748

Closed

Description

@dwalend

Steps:

  • Review alternatives to improve performance in Sysfs.java
  • Evaluate the performance with JMH
  • Consolidate changes with current architecture

Original Request:

The java code attached runs in about 100 to 140 milliseconds per iteration. Similar code using the ev3 classroom from LEGO runs each iteration in 2 to 4 milliseconds. 100 milliseconds is enough time for the robot to travel an inch or 3, which becomes significant quickly.

My question is - is the delay in the ev3 os streaming implementation, or in ev3dev-lang-java:2.6.2-SNAPSHOT code that reads and writes those streams? That'll tell me what to try first to speed it up my own code. If it's at the OS level then probably the best I can do is read and write the buffers in parallel. If it's in Java IO then maybe a JNI approach or an NIO loop could help.

I'm using ev3dev-lang-java:2.6.2-SNAPSHOT - on a stock EV3, not overclocked, with the stock ev3dev OS SDD card. It does touch the lejos SampleProvider to use the gyro sensor, but that seems to pass right through to Sysfs.readFloat(...).

Juan Antonio Breña Moral asked me to open an issue for the ev3dev-lang-java project here.

Activity

  1. dwalend commented on Nov 30, 2020

    @dwalend
    ContributorAuthor

    Here's the java code:

    package ev3.timing;
    
    import ev3dev.actuators.ev3.EV3Led;
    import ev3dev.actuators.ev3.EV3Led.Direction;
    import ev3dev.actuators.lego.motors.EV3LargeRegulatedMotor;
    import ev3dev.sensors.EV3Key;
    import ev3dev.sensors.ev3.EV3GyroSensor;
    import lejos.hardware.port.MotorPort;
    import lejos.hardware.port.SensorPort;
    import lejos.robotics.SampleProvider;
    
    public class TimingTest {
    
        //equivalent loop on just ev3 classroom is .3.6 / 100 = 0.0036 per iteration = 3.6 milliseconds - so it's a factor of about 100x
        public static void main(String[] args) {
            EV3LargeRegulatedMotor leftMotor = new EV3LargeRegulatedMotor(MotorPort.B);
            EV3LargeRegulatedMotor rightMotor = new EV3LargeRegulatedMotor(MotorPort.C);
            System.out.println("motors created");
    
            EV3GyroSensor gyroSensor = new EV3GyroSensor(SensorPort.S2);
            SampleProvider gyroSampleProvider = gyroSensor.getAngleMode();
            float[] gyroArray = new float[gyroSensor.sampleSize()];
            System.out.println("gyro created");
    
            warmUp(gyroSampleProvider,leftMotor,rightMotor);
    
            long[] timingResults = new long[10];
            for(int i = 0 ; i < timingResults.length ; i++) {
                long startTime = System.currentTimeMillis();
    
                //readHeading
                gyroSampleProvider.fetchSample(gyroArray, 0);
                float heading = gyroArray[0];
                //read each motor's odometer
                int leftOdometer = leftMotor.getTachoCount();
                int rightOdometer = rightMotor.getTachoCount();
                //set each motor's speed
                leftMotor.setSpeed(0);
                rightMotor.setSpeed(0);
    
                long endTime = System.currentTimeMillis();
                timingResults[i] = endTime - startTime;
                //todo set the array value
    
            }
            long total = 0 ;
            for(long r : timingResults ) {
                System.out.println(r);
                total = total + r;
            }
            System.out.println("average is "+(total/timingResults.length))   ;
        }
    
        static void warmUp(SampleProvider gyroSampleProvider,EV3LargeRegulatedMotor leftMotor,EV3LargeRegulatedMotor rightMotor) {
            long startTime = System.currentTimeMillis();
    
            //readHeading
            float[] gyroArray = new float[1];
            gyroSampleProvider.fetchSample(gyroArray, 0);
            //read each motor's odometer
            int leftOdometer = leftMotor.getTachoCount();
            int rightOdometer = rightMotor.getTachoCount();
            //set each motor's speed
            leftMotor.setSpeed(0);
            rightMotor.setSpeed(0);
    
            long endTime = System.currentTimeMillis();
        }
    }
  2. dwalend commented on Nov 30, 2020

    @dwalend
    ContributorAuthor

    Here's the ev3 classroom code that runs in 2-4 milliseconds per iteration.

    image

  3. self-assigned this
    on Dec 1, 2020
  4. added this to the v1.0.0 milestone on Dec 1, 2020
  5. jabrena commented on Dec 1, 2020

    @jabrena
    Member

    Hi @dwalend,

    many thanks for the issue.
    I will review this week, using the example provided.

    Juan Antonio

  6. jabrena commented on Dec 1, 2020

    @jabrena
    Member
    • Review imports
    • Create a benchmark with multiple implementations

    https://github.com/ev3dev-lang-java/ev3dev-lang-java/blob/master/src/main/java/ev3dev/utils/Sysfs.java
    https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#readAllLines(java.nio.file.Path,%20java.nio.charset.Charset)

    import java.io.File;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.nio.charset.Charset;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.nio.file.StandardOpenOption;
  7. JakubVanek commented on Dec 1, 2020

    @JakubVanek
    Contributor

    I will try to hack something together in C++ in the coming days to see what is the limit of the underlying OS.

  8. JakubVanek commented on Dec 1, 2020

    @JakubVanek
    Contributor

    I have an initial version of the C++ benchmark available.

    "Rolling-release" links (pointing at master, not the commit https://github.com/JakubVanek/ev3dev-lang-cpp-bench/commit/b01a3b22d6d4bbc3cecd23c53c214706d4e23e76):

    However, I've noticed that even though the benchmark sets the speed attribute, it doesn't order the motors to start moving. Is this intentional? I've followed this in the C++ program. I believe the situation with leJOS/ev3dev-lang-java is similar and you'd have to call forward() for the speed setting to take full effect.

  9. JakubVanek commented on Dec 1, 2020

    @JakubVanek
    Contributor

    -[ ] Review imports
    -[ ] Create a benchmark with multiple implementations

    @jabrena I'd check the ideas proposed in #652, while not everything is useful, the writeString method looks more optimized than the current one.

  10. JakubVanek commented on Dec 1, 2020

    @JakubVanek
    Contributor

    It seems that the compiler in Ubuntu 18.04 is too new to compile for ev3dev-stretch, I'll provide a binary built with a "universal" compiler (download here) that I was using for different C development.

  11. JakubVanek commented on Dec 1, 2020

    @JakubVanek
    Contributor

    EDIT: I'm going to use a arm-linux-musleabi-cross compiler from http://musl.cc/, they're available for Windows as well, so then a comparable setup should be available.

  12. dwalend commented on Dec 1, 2020

    @dwalend
    ContributorAuthor

    I've noticed that even though the benchmark sets the speed attribute, it doesn't order the motors to start moving. Is this intentional?

    That's correct. Starting the motors isn't in the control loop, so I left it out of the benchmark. That gives me a reason better than "I don't want to take the wheels off the robot, and don't want it crashing into stuff on my desk."

  13. 267 remaining items

  14. jabrena commented on Dec 25, 2020

    @jabrena
    Member

    The profilers works. Any other idea?

  15. JakubVanek commented on Dec 25, 2020

    @JakubVanek
    Contributor

    The profilers works. Any other idea?

    The performance measurement itself does work, but the last time there were only 0.0 and NaN values in the profiler results.

    "secondaryMetrics" : {
    "·gc.alloc.rate" : {
    "score" : "NaN",
    "scoreError" : "NaN",
    "scoreConfidence" : [
    "NaN",
    "NaN"
    ],
    "scorePercentiles" : {
    "0.0" : "NaN",
    "50.0" : "NaN",
    "90.0" : "NaN",
    "95.0" : "NaN",
    "99.0" : "NaN",
    "99.9" : "NaN",
    "99.99" : "NaN",
    "99.999" : "NaN",
    "99.9999" : "NaN",
    "100.0" : "NaN"
    },
    "scoreUnit" : "MB/sec",
    "rawData" : [
    [
    "NaN",
    "NaN",
    "NaN",
    "NaN",
    "NaN",
    "NaN",
    "NaN",
    "NaN",
    "NaN",
    "NaN"
    ],
    [
    "NaN",
    "NaN",
    "NaN",
    "NaN",
    "NaN",
    "NaN",
    "NaN",
    "NaN",
    "NaN",
    "NaN"
    ]
    ]
    },
    "·gc.count" : {
    "score" : 0.0,
    "scoreError" : "NaN",
    "scoreConfidence" : [
    0.0,
    0.0
    ],
    "scorePercentiles" : {
    "0.0" : 0.0,
    "50.0" : 0.0,
    "90.0" : 0.0,
    "95.0" : 0.0,
    "99.0" : 0.0,
    "99.9" : 0.0,
    "99.99" : 0.0,
    "99.999" : 0.0,
    "99.9999" : 0.0,
    "100.0" : 0.0
    },
    "scoreUnit" : "counts",
    "rawData" : [
    [
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0
    ],
    [
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0
    ]
    ]
    },
    "·stack" : {
    "score" : "NaN",
    "scoreError" : "NaN",
    "scoreConfidence" : [
    "NaN",
    "NaN"
    ],
    "scorePercentiles" : {
    "0.0" : "NaN",
    "50.0" : "NaN",
    "90.0" : "NaN",
    "95.0" : "NaN",
    "99.0" : "NaN",
    "99.9" : "NaN",
    "99.99" : "NaN",
    "99.999" : "NaN",
    "99.9999" : "NaN",
    "100.0" : "NaN"
    },
    "scoreUnit" : "---",
    "rawData" : [
    [
    "NaN",
    "NaN",
    "NaN",
    "NaN",
    "NaN",
    "NaN",
    "NaN",
    "NaN",
    "NaN",
    "NaN"
    ],
    [
    "NaN",
    "NaN",
    "NaN",
    "NaN",
    "NaN",
    "NaN",
    "NaN",
    "NaN",
    "NaN",
    "NaN"
    ]
    ]
    }
    }
    },

  16. jabrena commented on Dec 25, 2020

    @jabrena
    Member

    Hi @JakubVanek,

    this is a kind a result from JMH and indeed, I didn´t add to reduce the time invested in the tests but they works.
    It is a pity that you don´t believe in JMH but this is the official Java tool for MicroBenchmarking.

    Review in Internet, you will find positive results with JMH.

  17. JakubVanek commented on Dec 25, 2020

    @JakubVanek
    Contributor

    Hi @JakubVanek,

    this is a kind a result from JMH and indeed, I didn´t add to reduce the time invested in the tests but they works.
    It is a pity that you don´t believe in JMH but this is the official Java tool for MicroBenchmarking.

    Review in Internet, you will find positive results with JMH.

    I do admit that my initial opinions about JMH based on the first measured data in this thread were wrong. My evaluation was coming from the error margins; I thought this was the best JMH was capable of on EV3.

    However, after experiments, I found that JMH is capable of providing solid results even on the EV3 (this was done in parallel with the RtControlBench tests, see earlier comments). However, it seems that to get small error margins from JMH, I had to keep some things in mind (this is not specific to JMH though, any measurement of anything would be affected by this).

    • steady state need to be ensured (either the JIT has to be warmed up, or it has to be disabled altogether, or sufficiently small amount of measurements has to be done (but see below))
    • the more measurements (iteration count or measurementTime), the better
    • because JMH runs two JVMs in parallel (can be verified by running top when the benchmark is running), care needs to be taken to prevent a situation where one of the JVM's memory has to be pushed out to swap
    • presence of sensors in sensor ports can affect the resulting score due to the additional CPU load they create

    I'm also not saying that the stack profiler and GC profiler are broken in general, I just want to point out that from the data that I can access, it seems it didn't produce interpretable results in this specific environment.

  18. jabrena commented on Dec 25, 2020

    @jabrena
    Member

    Oki

  19. jabrena commented on Dec 27, 2020

    @jabrena
    Member

    @dwalend Any feedback?

  20. dwalend commented on Dec 27, 2020

    @dwalend
    ContributorAuthor

    I'm pretty pragmatic about how performance is measured. Whatever you like is fine, so long as it matches with the reality of how fast my kid can close a control loop. I saw useful values via System.currentTimeMillis().

    If the JMH profiler is available as a library you can probably run the profiler in the same JVM as the code you are observing to save the switching overhead. I'm not sure if that is of interest.

    And the same for NIO vs JNA vs JNI. Whatever performs best is the right answer.

    I like the advantage of an all-Java NIO fix because it takes me a lot less to explain what the code does to the kids I'm teaching. "This code reads the sensor the same way it would read a file. It's tweaked out a bit to read the file really fast," is pretty easy. In fact "It reads this many bytes or fewer," is helpful for inviting the kids a level deeper without a huge context switch.

    The next big step forward in performance is keeping the file handle open, at least on the NIO front. It's a big boost for not a lot of new concepts or complexity. Closable is extremely common, inescapable, and other people do a great job of explaining it.

    As for what API to supply - KISS is the best answer. Java's culture and community tends to bring in a lot of object-oriented hierarchy complexity that doesn't help a developer understand or use a library. Here on the EV3 it really matters. Restarts are frequent. Loading extra classes is really slow. Each extra layer of abstraction - especially classes - has a big cost, but not a lot of benefit. The kid plugged in the gyro sensor to read the robot's heading. The fact that it has the same API as the color sensor doesn't make up for the complexity of creating a float array to get one number - a number that is always an int. Discover the actual useful commonality and refactor to take advantage of it instead of forcing the internal programming model on people who use your library. Do a good job of exposing everything using a similar pattern, but do a great job with the simple common use cases.

    I especially want to discourage anything that involves making decisions about concurrency. The big lesson we learned while writing and proofing Concurrency in Practice was that concurrency was a really hard systemic problem best solved in outermost layers of code. Making the choice over-constrains the system. No one can predict what the right answer will be.

  21. jabrena commented on Dec 27, 2020

    @jabrena
    Member

    Thanks for your comments @dwalend,

    The next big step forward in performance is keeping the file handle open, at least on the NIO front. It's a big boost for not a lot of new concepts or complexity.

    Tomorrow, I will clean the branch and I will merge to master and release the library in order to close this issue too:
    #739

    Tomorrow, I will open a new issue to begin with the next level of optimisation.

    I especially want to discourage anything that involves making decisions about concurrency. The big lesson we learned while writing and proofing Concurrency in Practice was that concurrency was a really hard systemic problem best solved in outermost layers of code.

    Agree with you.

    In the next iteration, we will remove the following blocking delay in a more elegant way:

            this.detect(LEGO_PORT, port);
            if (log.isDebugEnabled()) {
                log.debug("Setting port in mode: {}", TACHO_MOTOR);
            }
            this.setStringAttribute(MODE, TACHO_MOTOR);
            Delay.msDelay(1000);
            this.detect(TACHO_MOTOR, port);

    Thanks @dwalend and @JakubVanek for the contributions.

    Juan Antonio

  22. jabrena commented on Dec 27, 2020

    @jabrena
    Member

    In progress:
    #761

  23. jabrena commented on Dec 27, 2020

    @jabrena
    Member
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions