The tickcount trick

Stats

74 visits, 109 views

Translations

This tutorial hasn't been translated.

Tools

Ok now we're getting into the serious stuff, the meat, the juice, the gold, the real deal, the thing.

This is the single most important trick for easily gaining performance for free.

It's low effort, and can save a ton of CPU.

What is it??

Just add Compare two values: tickcount % 2 = 0 as the first condition of your big events.

Most of the time, you run stuff on every tick, but you actually don't need to do that. If you're writing code that updates an AI, checks for lots of collisions, or checks for win conditions to trigger your end screen, you actually don't need the code to react instantly to what happened.

So instead of running that code every tick, you can run it every two ticks. Hence tickcount%2 = 0.

Hell, you can probably run it every 3 ticks, or even every 30 ticks and no one will notice.

Well... speedrunners will.

Anyway, it's a simple trick and an even simpler calculation. If you do something every 30 frames compared to doing it on every frame, then that thing will be 30 times less heavy on your CPU.

Congrats, you have optimized your code.

Also works with "Every X seconds" but keep in mind that this is time scale dependent and will run slower or faster if you change the time scale.

Next Tutorial In Course

  • 4 Comments

  • Order by
Want to leave a comment? Login or Register an account!
  • Forgive my ignorance, but how to implement

    "Compare two values: tickcount % 2 = 0" in Construct?

    Maybe I'm just being dense right now, but could you add a screenshot of what this would look like in the event sheet?

    • Hi, no worries.

      In system conditions there is a condition named "compare two values"

      Put tickcount % 2 in the first field

      = (equal) in the second (it's a dropdown)

      0 in the third

      • Thank you, that's helpful. One more question...

        What does the "% 2" mean? I'd like to understand exactly what is happening here.

        • % is the modulo operator. Basically a%b returns the rest of the euclidian division of a by b. Put in other words, you remove b from a as long as a > b

          12%7 = 5

          100%10 = 0

          3%8 = 3

          So what that means is that it will execute the action only when tickount%2 is equal to 0. This is true when tickount is even. So it will only execute the action when tickcount is even AKA every two frames.

          Changing the number after the modulo increases the number of frames it will wait before performing the action.