# Is millis() heavy on CPU program efficiency?

**URL:** <https://discourse.processing.org/t/is-millis-heavy-on-cpu-program-efficiency/23266>\
**Category:** p5.js\
**Created:** [August 14, 2020, 11:01pm UTC](https://discourse.processing.org/t/is-millis-heavy-on-cpu-program-efficiency/23266 "2020-08-14T23:01:07Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![mnoble](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/mnoble/32/99_2.png) [@mnoble](https://discourse.processing.org/u/mnoble)\
**Post date:** [August 14, 2020, 11:01pm UTC](https://discourse.processing.org/t/is-millis-heavy-on-cpu-program-efficiency/23266/1 "2020-08-14T23:01:07Z")

</div>

Hello Forum,

I am working a project running p5js sketches from Open Processing on mobile devices. I have the need to create a series of timed events with millis() but this slowing things down greatly! Are there efficient strategies for multiple events timed that are better than millis()?

Thanks for your help!

Margaret

---

<div class="post-metadata">

**Author:** ![glv](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/glv/32/18785_2.png) [@glv](https://discourse.processing.org/u/glv)\
**Post date:** [August 14, 2020, 11:33pm UTC](https://discourse.processing.org/t/is-millis-heavy-on-cpu-program-efficiency/23266/2 "2020-08-14T23:33:04Z")

</div>

Hello,

I can’t comment on efficiency…

In Processing I have used frameCount:

> [@Animation that transitions using frameCount](https://discourse.processing.org/t/animation-that-transitions-using-framecount/15378):
>
> A very simple example that transitions through scenes over time: // Author: GLV // Date: 2019-11-10 // Description: // Animate over time using frameCount // A very simple example that: // Uses frameCount to keep track of time // Fades in and out by modifying alpha component of HSB color // Cycles through HSB colors int scene = 0; int sec = 60; float alpha = 0; void setup() { size(500, 500); textSize(36); textAlign(CENTER, CENTER); colorMode(HSB, 360, 100, 100, 100); } void draw()…

> **[reference | p5.js](https://p5js.org/reference/#/p5/frameCount)**
>
> p5.js a JS client-side library for creating graphic and interactive experiences, based on the core principles of Processing.

I do not know how stable the frameRate is using P5.js on an Android.  
Your mileage may vary depending on what you’re sketch is doing; I often monitor frameRate to see if sketch is slowing things down and work to optimize code.

> **[reference | p5.js](https://p5js.org/reference/#/p5/frameRate)**
>
> p5.js a JS client-side library for creating graphic and interactive experiences, based on the core principles of Processing.

`:)`

---

<div class="post-metadata">

**Author:** ![noel](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/noel/32/213_2.png) [@noel](https://discourse.processing.org/u/noel)\
**Post date:** [August 15, 2020, 4:13am UTC](https://discourse.processing.org/t/is-millis-heavy-on-cpu-program-efficiency/23266/3 "2020-08-15T04:13:19Z")

</div>

I found this interesting enough to test, and you are right; using millis() in a loop drove my CPU use up to a level of 55%!  
Using frameCount (as glv suggested), in a loop , does not give significant alternation.

---

<div class="post-metadata">

**Author:** ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)\
**Post date:** [August 15, 2020, 5:34am UTC](https://discourse.processing.org/t/is-millis-heavy-on-cpu-program-efficiency/23266/4 "2020-08-15T05:34:08Z")

</div>

The [_frameCount_](https://p5js.org/reference/#/p5/frameCount) approach is very light but is bound by the **frameRate()**:  
[p5js.org/reference/#/p5/frameRate](http://p5js.org/reference/#/p5/frameRate)

Another good performant approach is **setTimeout()**:

> **[WindowOrWorkerGlobalScope.setTimeout()](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout)**
>
> The setTimeout() method of the WindowOrWorkerGlobalScope mixin (and successor to Window.setTimeout()) sets a timer which executes a function or specified piece of code once the timer expires.

I’ve got a wrapper class for it named Countdown btW:

> **[Countdown Class](http://bl.ocks.org/GoSubRoutine/1a0d21828319cf18fecf44101764bd60)**
>
> GoSubRoutine’s Block 1a0d21828319cf18fecf44101764bd60

---

<div class="post-metadata">

**Author:** ![noel](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/noel/32/213_2.png) [@noel](https://discourse.processing.org/u/noel)\
**Post date:** [August 15, 2020, 11:39am UTC](https://discourse.processing.org/t/is-millis-heavy-on-cpu-program-efficiency/23266/5 "2020-08-15T11:39:16Z")

</div>

@GoToLoop Thanks for pointing me out to the java timer utilities.  
The most concise code I could make is this one.

```auto
import java.util.Timer;
import java.util.TimerTask;

void setup() {
  size(500, 500);
  background(255);
  Timer timer = new Timer();
  TimerTask task = new TimerTask() {
      public void run() {
      println(millis());
    }
  };
  println("Start time = "+millis());
  println("Sheduled 50ms timer task = 3 seconds");
  timer.schedule(task, 3000, 50);
}

```

---

<div class="post-metadata">

**Author:** ![mnoble](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/mnoble/32/99_2.png) [@mnoble](https://discourse.processing.org/u/mnoble)\
**Post date:** [August 15, 2020, 8:43pm UTC](https://discourse.processing.org/t/is-millis-heavy-on-cpu-program-efficiency/23266/6 "2020-08-15T20:43:34Z")

</div>

Thank you to all who helped me wrap my head around millis() and programming timers!

---

<div class="post-metadata">

**Author:** ![mnoble](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/mnoble/32/99_2.png) [@mnoble](https://discourse.processing.org/u/mnoble)\
**Post date:** [September 21, 2020, 4:28pm UTC](https://discourse.processing.org/t/is-millis-heavy-on-cpu-program-efficiency/23266/7 "2020-09-21T16:28:57Z")

</div>

Hi GoToLoop,

This solution is a little over my heard 🙂 Is this something I could use on OpenProcessing with p5Js to solve this problem:

> [@Timers Not Frame Rate Dependent & Starting On Demand - Oh Please Oh Please slight\_smile](https://discourse.processing.org/t/timers-not-frame-rate-dependent-starting-on-demand-oh-please-oh-please/23994):
>
> Hello Forum, I am making interactive visualizers that coordinate with sequenced visual automations and sound. I need to start a timer after a button is pushed (which I am pretty sure you can’t do with millis()) and I can’t use the frameCount() solution because I have just learned that computers vs. phones vs. tablets all have the possibility of different frame rates (30,60, even 120 sometimes) - animation timings will be out of sync for several devices. I have witnessed timings play out really…

---

<div class="post-metadata">

**Author:** ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)\
**Post date:** [September 21, 2020, 5:13pm UTC](https://discourse.processing.org/t/is-millis-heavy-on-cpu-program-efficiency/23266/8 "2020-09-21T17:13:15Z")

</div>

> [@mnoble](#):
>
> Is this something I could use on OpenProcessing with p5Js to solve this problem:

There are at least 3 ways to tackle that:

1. Use p5js’ own [**millis()**](https://p5js.org/reference/#/p5/millis).
2. Use JS’ [**setTimeout()**](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout).
3. Use my [Countdown](http://bl.ocks.org/GoSubRoutine/1a0d21828319cf18fecf44101764bd60#countdown.js) class, which is a wrapper for [**setTimeout()**](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout) btW.

If you decide to pick my “library” class, you just need to copy & paste the contents of its file “countdown.js” onto a new tab from OpenProcessing.

The other file “sketch.js” is merely some silly example on how to use the wrapper class Countdown.

> [@mnoble](#):
>
> This solution is a little over my head. 🙂

Basically what the class Countdown does is set its property _done_ to `true` when **setTimeout()** triggers.

So you’re gonna need to continuously poll the status of property Countdown::_done_ in order to know whether the wait time is over.

The milliseconds wait time is stored in property Countdown::_delay_ and it’s initialized by the argument passed to constructor.

The wait time begins when we call the method Countdown::**start()**, which automatically calls **clearTimeout()** to cancel previous **setTimeout()** & sets Countdown::_done_ to `false`.

If you need different wait times just create more instances of class Countdown.

---

<div class="post-metadata">

**Author:** ![mnoble](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/mnoble/32/99_2.png) [@mnoble](https://discourse.processing.org/u/mnoble)\
**Post date:** [September 21, 2020, 10:43pm UTC](https://discourse.processing.org/t/is-millis-heavy-on-cpu-program-efficiency/23266/9 "2020-09-21T22:43:23Z")

</div>

Hi GoToLoop - first thank you! I have been playing with your ideas and testing some others from other code friends too. In the end, I found a solution with [setInterval()](https://www.w3schools.com/jsref/met_win_setinterval.asp) which worked best for my particular project. Here’s a reduced version of how it works for me:

```auto
'use strict';

var button;

let timer = 0;
let startProgram = false;
let loaded = false;

function setup() {

    loaded = true;
    beginButton()
    createCanvas(windowWidth, windowHeight);

    console.time('time')
    noSmooth(); //does this improve running?
    console.timeEnd('time')
}

function beginButton() {
    let col = color(255);
    let col2 = color(0);
    button = createButton("begin");
    button.mousePressed(beginExperience);
    button.position(width / 2 - 30, height - 40);
    button.size(60, 25);
    button.style('background-color', col);
    button.style("color", col2);

}

function draw() {

    background(0);
    if (startProgram == false || loaded == false) {
        showLoading();
    }

    //start automations & timer when button pressed	
    else {
 		
			if (timer<=5){
				fill (0,255,0);
			}
			else if (timer>5&&timer<=10){
			fill (255,0,0);
			}	
			else if (timer>11){
			fill (0,0,255);
			}	
      ellipse(mouseX,height/2,100,100);
			
			//timer report
			textSize (20);
		  text (timer,width/2,100);
			
    } //close timed events/experience screen

} //close draw

function beginExperience() {
    setInterval(() => {
        timer++;
    }, 1000)
    button.remove();
    startProgram = true;
}

function touchMoved() {
    return false; //this prevents dragging screen around on mobile
}

function showLoading() {
    background(0);
    textAlign(CENTER, CENTER);
    rectMode(CENTER);
    text('loading...', width / 2, height - 30);
}

```
