You are reading a single comment by @maze1980 and its replies. Click here to read the full conversation.
  • While it's an old thread, starting with the code provided

    arr[n++] = (Math.random() * 255) * 0.25; 
    

    I tried to optimize, and see what's possible:

    const pin = NodeMCU.D5;
    const leds = 24;
    const arrl = 24*3;
    var arr = new Uint8ClampedArray(arrl);
    var animate = function(){
      for(var a = 0; a < arrl ; a++) {
        //0.01s
        //no calculation at all
        //0.06s
        //arr[a] = Math.random() * 64;
        //0.071s
        //arr[a] = Math.random() * 63.75;
        //0.075s
        //arr[a] = Math.random() * 255 * 0.25;
        //0.097s
        //arr[a] = Math.round(Math.random() * 63.75);
        //0.100s
        //arr[a] = Math.floor(Math.random() * 63.75);
      }
      require("neopixel").write(pin, arr);
    };
    

    The duration measured is included in the code sample, and it's obvious that the neopixel write itself is fast, there's no optimization needed. However filling every array index and calling Math functions makes things slow. To avoid this I did the following:

    var arr1 = new Uint8ClampedArray(leds);
    var arr2 = new Uint8ClampedArray(leds);
    var arr3 = new Uint8ClampedArray(leds);
    for(var a = 0; a < arrl ; a++) {
      arr1[a] = Math.random() * 64;
      arr2[a] = Math.random() * 64;
      arr3[a] = Math.random() * 64;
    }
    for (i=1; i<10; i++) {
        if (i===1) require("neopixel").write(pin, [].concat(arr1,arr2,arr3));
          else if (i===2) require("neopixel").write(pin, [].concat(arr1,arr1,arr1));
          else if (i===3) require("neopixel").write(pin, [].concat(arr1,arr3,arr2));
          else if (i===4) require("neopixel").write(pin, [].concat(arr3,arr2,arr1));
          else if (i===5) require("neopixel").write(pin, [].concat(arr1,arr3,arr1));
          else if (i===6) require("neopixel").write(pin, [].concat(arr3,arr2,arr3));
          else if (i===7) require("neopixel").write(pin, [].concat(arr3,arr2,arr3));
          else if (i===8) require("neopixel").write(pin, [].concat(arr3,arr3,arr2));
          else if (i===8) require("neopixel").write(pin, [].concat(arr3,arr2,arr3));
          else if (i===9) require("neopixel").write(pin, [].concat(arr3,arr3,arr2));
          else require("neopixel").write(pin, [].concat(arr3,arr3,arr3));
      }
    

    This code is 10x faster. However you should note that [].concat() returns a standard array with three (or four) UInt8Arrays inside. (concat and splice are not implemented for UInt8Arrays, so you can't use these functions). Running this code with standard arrays more than doubles the execution time. When doing rainbow effects or other smooth animations you would want to use UInt8Arrays as containers for RGB values, and standard arrays for these containers (if you have enough variables and RAM available).

About

Avatar for maze1980 @maze1980 started