Example Concurrent Operations

From Efficient Java Matrix Library
Revision as of 07:05, 7 July 2021 by Peter (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Concurrent or Mult Threaded operations are a relatively recent to EJML. EJML has traditionally been focused on single threaded performance but this recently changed when "low hanging fruit" has been converted into threaded code. Not all and in fact most operations don't have threaded variants yet and it is always possible to call code which is purely single threaded. See below for more details.


External Resources:

Example Code

/**
 * Concurrent or multi-threaded algorithms are a recent addition to EJML. Classes with concurrent implementations
 * can be identified with _MT_ in the class name. For example CommonOps_MT_DDRM will contain concurrent implementations
 * of operations such as matrix multiplication for dense row-major algorithms. Not everything has a concurrent
 * implementation yet and in some cases entirely new algorithms will need to be implemented.
 *
 * @author Peter Abeles
 */
public class ExampleConcurrent {
    public static void main( String[] args ) {
        // Create a few random matrices that we will multiply and decompose
        var rand = new Random(0xBEEF);
        DMatrixRMaj A = RandomMatrices_DDRM.rectangle(4000, 4000, -1, 1, rand);
        DMatrixRMaj B = RandomMatrices_DDRM.rectangle(A.numCols, 1000, -1, 1, rand);
        DMatrixRMaj C = new DMatrixRMaj(1, 1);

        // First do a concurrent matrix multiply using the default number of threads
        System.out.println("Matrix Multiply, threads=" + EjmlConcurrency.getMaxThreads());
        UtilEjml.printTime("  ", "Elapsed: ", () -> CommonOps_MT_DDRM.mult(A, B, C));

        // Set it to two threads
        EjmlConcurrency.setMaxThreads(2);
        System.out.println("Matrix Multiply, threads=" + EjmlConcurrency.getMaxThreads());
        UtilEjml.printTime("  ", "Elapsed: ", () -> CommonOps_MT_DDRM.mult(A, B, C));

        // Then let's compare it against the single thread implementation
        System.out.println("Matrix Multiply, Single Thread");
        UtilEjml.printTime("  ", "Elapsed: ", () -> CommonOps_DDRM.mult(A, B, C));

        // Setting the number of threads to 1 then running am MT implementation actually calls completely different
        // code than the regular function calls and will be less efficient. This will probably only be evident on
        // small matrices though

        // If the future we will provide a way to optionally automatically switch to concurrent implementations
        // for larger when calling standard functions.
    }
}