Jump to content
  • Advertisement
Liquifire

Optimization Should timers in an engine be on separate threads?

Recommended Posts

I'm making an small 2D engine using Kha and I have a timer class, which basically simply either waits a certain amount of time to call a function, or repeatedly calls a certain function after every x seconds. I simply want to know if I should have timers run on different threads. I'm aware that makes sense, but I might use many timers in a game for example, would that still be okay? Also I'm currently writing an animation components, which waits every x seconds to draw another image using the timer class. And in a normal 2D games, I would have many objects with animations on them, other than the other timers. So I just wanted to ask people who have more experience and knowledge than I have what I should do for timers: Either leave them on the same main thread, or make them run on different threads. Thanks in advance.

Share this post


Link to post
Share on other sites
Advertisement

The main question is what else runs in a different thread of your game? It dosent make sense to split a sepratate thread for timers if you have 10 other threads running whatever logic in the background.

Animation is usually done using the time delta from last frame to current frame. I don't know any kind of engine that uses a separate timer class for anymations. Time delta is calculated by getting the time on the start of last frame and the time of the start of current frame, this way you know how much time expired between your two frames and can mult that factor to anything, any animation, any movement and whatever you also have.

In my engine, I use a pooling for tasks that may run in any thread my scheduler gives it so I start a timer in one thread and check for it in another one for example on update loop or when reaching a code part that utilizes the timer. This is the reason why timers and timing functions write in there docs to wayt "at least a minimum ammount of time before executing callback". This is because you won't have exact timing even if you run a timer thread because threads may schedule from the OS and if you have a large list of timers, it becomes an O(n) operation until your callback returns.

I use high precision timers, so my "Timer-Class" is just an uint64 value with the CPU tick count. To get the time elapsed I then throw that into a measure function that calculates the difference between my 'timer' and current CPU ticks, thats it.

Timers are in my experience barely used except for gameplay features, anything else that is frequently updated, like ingame-time for example, is usually bound to the time delta of the frame

Share this post


Link to post
Share on other sites

It's probably overkill unless the resulting function call is also on another thread, and even then it might be overkill. You're not going to gain much putting a timer on another thread, except possibly the headache of debugging resulting threading issues. ;) 

If you find you need to, there's nothing stopping you from just spawning the timer on the separate thread as needed - there's no need to incorporate threading behavior in the timer itself. 

Share this post


Link to post
Share on other sites
On 6/9/2018 at 9:49 PM, Liquifire said:

I might use many timers in a game for example, would that still be okay?

For being "okay", it basically boils down to costs and purposes.

Threads have a cost. There is a relatively high cost to create a thread, and threads have some processing overhead. The functionality is written and provided by the operating system rather than code you write in your application, but it is still code that gets run, it still has a cost to run, and the work of scheduling, context switching, and otherwise manipulating the processing threads still needs to happen.

If your game is still running anyway, using your own timers to call functions has far less overhead than a thread. You run a test against timers and call a function when the condition is hit. The cost and overhead are minimal.

If your game isn't actively running, perhaps you're a very slow-paced game that isn't running at interactive speeds and the processes are mostly sleeping or otherwise blocked, using threads may be more convenient. Also sometimes threads are used for organizational purposes, if you're doing that it may make sense to use them to help wake a task.

 

In general I'd do what you can to avoid creating new threads. Ensuring data flows correctly and timing works correctly is incredibly hard. Multiprocessing introduces an entirely new dimensionality to bugs as race conditions, resource starvation, and deadlocks/livelocks/interdependencies can be quite difficult to untangle and debug.

Share this post


Link to post
Share on other sites
Posted (edited)

Timers in games fall into 2 categories: Utilities and in-game/gameplay timers.

Utility timers run on separate threads and trigger system events etc.  An example that used to be common (but should never be done) is a timer to run the game loop.  Timers to update the sound system, to load data, to run physics, etc., are examples of utility timers.  They keep the game running, but are not specific to the game.  They run on system threads.

A game timer is meant to trigger an in-game action.  They are gameplay-critical.  They run in the main game thread and are updated at a specific point within the game loop.  If the game lags, the timers lag.  They can be based on game time, pausable game time, frames, ticks, logical updates, or other game-related timing mechanisms.

 

So which do you need?
Neither. You’re updating an animation.  This is definitely not the purpose of timers.

You draw the correct frame of an animation by determining how much time has passed since the animation began, which you do by simply accumulating it each tick.

If you Tick() for 33333 microseconds, each tick your objects add 33333 to their current animation time (which is stored in microseconds).

Which frame to draw simply depends on how fast they animate.
If I am drawing at 2 seconds in and the animations are running at 24 FPS then I should be drawing frame 48.

Why would you implement a whole timer system instead of a multiply and divide?


L. Spiro

Edited by L. Spiro

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Advertisement
  • Advertisement
  • Popular Tags

  • Similar Content

    • By davejones
      I have been doing research into optimising 3d models in 3ds max. There seems to be so many different ways to optimise 3d models. I am unsure which method is the best and have been trying different tools such as the pro optimizer tool in 3ds max. Does anyone know the best way to optimise 3d models in 3ds max? I am trying to reduce the file size whilst maintain a high quality model. So produce a low polygon model which looks like a high polygon model. 
    • By Phanoo
      It's for a 2D game, but the question is broader...
      Let's say I want to have some object (eg. a projectile) interact with some other object (eg. a button) so the projectile thrown by the player can trigger the button. I know there could be several ways of doing this, like the brute force o(n^2) method, the 'optimized' method using a QuadTree or spatial hash... But i thought about another method, and was wondering if it's a good idea or not :
      It consist of iterating two times over the active game object list:
      - the first looks for projectile objects, storing their pointers into some array
      - the second looks for button objects, checking if collision occurs with one of the projectiles in the array
       
      Other specific collisions checks could be done with this method, but that would need multiple pointer lists.
       
      Do you know how old games (like thoses on Genesis, we're talking about 8Mhz cpus...) achieved that ?
      Should I just implement some spatial hashing and checking all the collisions inside the restrained area, avoiding storing pointer lists ?
       
      My levels would have about 1000 objects, i'm not that much concerned about performance since I know how to optimize, but more on finding an elegant/simple way of doing this. I'd like keeping the code small and maintainable.
    • By Gezu
      Hi,
      I'm working on Warriorb for about 2,5 years now and recently we made a playable version of the first part of the game. There are still some elements missing (mostly vfx and sfx) but most of it is close to final.
      I would love to hear what do you think about our game so far. Any critique, feedback, idea or tip is appreciated.
      If you are interested send me a pm and I will give you a steam key for the game.
      I'm eager to receive your feedback:
      Gézu
    • By Erik Nivala
      So, as the title says i am trying to figure out a good way sync all that information with other players in Unity. My problem is that i can't come up with a good solution since i am used to creating classes for everything e.g. attachments are its own class and then the weapon would save a reference to that attachment. But since you can't send custom classes over [Command] & [ClientRPC] i am a little stuck. A solution for this would be giving each attachment for a slot a unique ID and then passing the ID to other player but i feel like that is very error prone if other ppl add a new attachment or the IDs get mixed up.
      Is there a "standard" way that this is usually done that i am missing?
      I am fairly new to programming so any help is appreciated!
    • By Woody Stevens
      Hi,
       
      I am looking for a TCP or HTTP networking library similar to Lidgren (UDP).
       
      This is primarily for sending game map data and potentially other large messages from Server to Client.
       
      I do want to keep Lidgren for my chat messages, player position, small fast updates etc. I especially love the flow of data and the library usage in general, so any libraries of a similar style would be excellent. Preferably something open source, free and reliable.
      I also must be able to swap between localhost and an ip address with ease, like Lidgren, as I run a server for singleplayer/mp/lan.
       
      My game maps are similar to minecraft, but it is 2d and only one Z-level, so i'm sending a jagged array of Tile object data (currently only enum TileID.Grass) down the pipe to the Client. Problem is if i'm sending a large map 1024 x 1024 tiles down the to client that's quite a lot of data, and Lidgren is relatively slow to build the writes (before the message is even sent!). It is fine when i'm using smaller maps < 512 x 512 ( xTiles * yTiles ).

      I know about chunking and will look into implementing this later, whilst taking into account the user's position in the world to only send nearby chunks.
       
      An example of my code that can be slow:
      private void WriteWorld(NetOutgoingMessage outgoing) { try { var world = WorldManager.Instance.CurrentWorld; outgoing.Write(world.XTiles); outgoing.Write(world.YTiles); for (int x = 0; x < world.XTiles; x++) { for (int y = 0; y < world.YTiles; y++) { // Write Tile obj data outgoing.Write((int)world.Tiles[x][y]); // <-------- Slow here when xTiles and yTiles are each > 512 ! } } } catch (Exception ex) { // log send error } }  
      I'd love to hear from you guys, especially if any of you have come across a similar challenge.
    • By tromtrom
      I've been doing some research on delta compression (used and described in the Quake3 doc http://trac.bookofhook.com/bookofhook/trac.cgi/wiki/Quake3Networking,), and I'm looking for some clarifications on that topic please if possible.
      I understand that the delta compressed state is the difference between any given world states, meaning that if we store the state of every entity in a world state at every tick, the difference would be only the states of entities that changed between these two world states.
      Now when sending back the delta state to the client, do we go as far as only mentioning the properties that changed? Let's say a character moved only on X axis but didn't move on the Y axis between two states, are we sending to the client the whole state (x, and y) or only the new x position?
      If that's the case and let's assume there are a few more properties that describes a character, how can the client identify which properties have actually changed when rebuilding the information from binary data.
       
    • By Catalin Danciu
      Hello,
      In the hopes that my thread is not off-topic or offensive in any way, I dare to ask the following "noob" question:
      what would be the correct way to create sprite animations from 2D *.bmp files?
      I have for reference the 2001 game  Desperados:Wanted Dead or Alive.
      with the help of some tools i found , I was able to extract files containing what seems to be animation frames and frame shadow masks for animating a horse.
      Attached are the archived assets.
      My goal is to recreate the demo level of the game using Unity, for educational purposes.
      I have started by loading the background map layer (also a large bmp file), and next step is to load a 2d character object and animate on the perspective.
       
      Horse_Brown.rar
    • By JoAndRoPo
      While going through a Game Design Document Template, I came across this heading - Core Game Loop & Core Mechanics Loop. 
      What's the difference? Can you provide some examples of an existing game?  Suppose if I am including these topics in a Game Design Document, how should I explain it so that my team can understand? 
    • By Scouting Ninja
      So I have hundreds of moving objects that need to check there speed. One of the reasons they need to check there speed is so they don't accelerate into oblivion, as more and more force is added to each object.
      At first I was just using the Unity vector3.magnitude. However this is actually very slow; when used hundreds of times.
      Next I tried the dot-product check:  vector3.dot(this.transform.foward, ShipBody.velocity) The performance boost was fantastic. However this only measures speed in the forward direction. Resulting in bouncing objects accelerating way past the allowed limit.
       
      I am hoping someone else knows a good way for me to check the speed with accuracy, that is fast on the CPU. Or just any magnitude calculations that I can test when I get home later.
       
      What if I used  vector3.dot(ShipBody.velocity.normalized, ShipBody.velocity)?
      How slow is it to normalize a vector, compared to asking it's magnitude?
    • By macmanmatty
      I have   spirtes that will be turned into animation images  for  the game actors.  What would be the best way to change the weapon / armor for each actor?  IE walking with sword swinging sword  then when he equips axe walking with axe  swinging axe  ECT.  Same for armor? Have sheets with  the weapons and armor and then overlay them on to the base spirte when the user changes the weapon  or have premade sheets  with all of the various combos of  armor / weapons  that the solider can have and then just grab the ones needed for the current selection. I'm thinking the first option is better, but are there any other better ways?
  • Advertisement
  • Popular Now

  • Forum Statistics

    • Total Topics
      631392
    • Total Posts
      2999742
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!