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

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 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?
    • By HomeBrewArcana
      Hey All,
      I'm looking to get into the gaming industry. I've skirted around the idea for a long time, always thinking that I couldn't do it. I've finally decided to take the plunge.
       
      My question is whether it's worth going to school for game design/coding etc. I've been writing content for paper games for a while, and have a good idea of story and some basic design. But I have next to no technical know how. 
       
      My instinct is that such things can be learned with a lot of practice, video tutorials, and more practice. I've also heard that a degree is not really that important, since you get hired based on your portfolio/prototypes. Why not just make the games?
      But won't a degree help with contacts and mentoring--I'm not a great networker.
       
      Of course, it'll plunge me into more debt, but...
      If anyone has advice, let me know. Also any idea of a program to start with: Game Maker, Unity, Godot, Construct, Stencyl--I've heard good things about them all, so much so that I don't know which would be best to start with!
       
      Thanks
    • By Developer Dre Reid
      Hello fellow game devs I am seeking some answers to a somewhat simple question. Now I always thought that when a dev was going to work on a new game to publish he/she should keep some aspects secret infill time to release then he/she can give out needed information pertaining to the game to the public as a marketing tactic. However I had a discussion with other game devs who stated that my way was somewhat not right and the only reason I had such thoughts was due to me being a smaller indie dev who was afraid of having my idea stolen. 
      Therefore I would honestly like to know if my way was right or were the other devs correct. If I were to start working on a new game and give out information about it online via social media would I be risking my idea being stolen and it being made faster and better by another developer or team of developers. Am...Am I paranoid??? 
    • By Aaron Marsden
      Hey everyone! 
      My name is Aaron and I’m a writer, gamer, and marketer/campaign manager for PowerSpike, a startup in the Twitch space. For the past two years, I’ve had the opportunity to build and run professional Twitch influencer marketing programs for some great brands (a few clients include Soylent, Camp Mobile, CreativeLabs, and more). 
      I’ve been obsessed with Twitch as both an entertainment and marketing platform since 2014. Before entering the world of marketing, I was a broadcaster and a content creator myself and made YouTube videos in my spare time. 
      Recently many game developers have shown interest in collaborating with Twitch streamers to promote their games -- and I think I can help! 
      I’ve learned so much about entertainment and community development from studying the growth of popular streamers since then, and my current position has allowed me to learn an incredible amount about the process of promoting a product/game/service’s message to a large audience with the help of Twitch streamers. 
      I’d love to share what I’ve learned with anyone who has questions. Ask me anything! 

      If you’d like, you can follow me on Medium at https://medium.com/@aaronmarsden -- that's where I'll be posting both personal and PowerSpike articles on game dev marketing. I also just released my first article, "The Ultimate Guide for Promoting Your Game with Twitch Influencers," here on GameDev.net! You can check it out here:
      Thanks everyone!
    • By shadow_archer
      hello!
      so i had this idea of a game i wanted to make that i had in mind for years and i wanted to try to execute it (at least partiality).
      problem is, i don't really know what kind of game style this game can fall under and i don't really know where to start learning sources and design wise :/ .
      i want to create a management style game and all the controls the user has are through a menu of some sort similar to this (this particular example is from a game called '911 operator' by jutsu games):

      to find more information about how i can create such a game i really want to know what's the name of this style of game, mostly GUI controlled game.
      aside from that i'm looking for a bit of advice,
      which engine would be best for such a game? i'm fluent in C++,C# and python so any game engine you can throw at me is great!
      are there any good sources to learn from before jumping into this kind of game, tutorials of some sort perhaps?
       
      thanks so much to anyone who answers, this really means a lot to me!
    • By callmevivi
      Hi! 
      So, I've recently thought of a nice twist to a hack and slash-type zombie game that I'd love to make (mostly so that no one can steal the idea I'm not gonna elaborate to much on the story, but that should be no issue to help me, I think).
      But my problem here is that I have little to no knowledge of coding. I AM willing to learn, but I'd rather not have to develop 50 games before I've learned how to develop the game I actually wanna make. I'm just a hobbyist. I don't have that kind of endurance for this.
      The game I'm looking to develop is basically just your typical Player having to fight their way through masses of zombies in a city towards a certain safe place, going from location (check-point) to location.
      The only controls I really want for the player to have are:
      -to interact with objects (like talk to people aka trigger a dialogue or cutscene, pick up objects like weapons, have commentary appear when interacting with something (like the player clicking on a corpse and triggering the player thinking "Please, don't attack me to. ... Thank you very much, Sir.". All of this could be established with simply triggering a cutscene though.),
      -move with the arrow keys or ASWD,
      -have a health bar (not necessarily displayed, I just want the player to actually be able to die if they get gnawed by too many zombies)
      -and hack away at zombies coming towards the player. Just let out all your frustration by bashing in their faces, maybe have a satisfyingly-bloody animation when they die. 
      -Hopefully have companion characters fight zombie hordes with you. (Although I could get creative and find excuses not to have the side-characters fight with you)
      -No jumping required.
      -Inventory would be nice but not necessary either. 
      -Saving your current game progression manually would be great, but could be done with check-points, too.

      Primary focus of the game would be just having fun hacking away at zombies and getting to know the characters, who I hope to make worth getting to know. 
      I've been researching the internet for game engines for weeks now but I haven't really found one that seemed helpful to me, mostly because the reviews are full of vocabulary that as an absolute newbie I understand none of. So, whenever I read the cons for an engine in the review I understand very little of it.
      Although an engine that requires absolutely no coding and still be able to perform all of this would be an absolute dream come true, I believe that's quite impossible to find. The only non-coding engines I've come across so far are absolute garbage due to limits, buggy, underdeveloped, or abandoned by their creators. I'm willing to learn coding, I'm not afraid of it as long as there are tutorials and templates out there, too. 
      As I'm a hobbyist I'd rather not pay for an engine or to export my game. I'm most-likely not going to sell my game for money and if I do it won't be expensive at all no matter how much time I'd invest in it. 
      Obviously the game would need to either be open source or let me publish and distribute the game freely.
      The only game engine I've found so far that I believe I'd understand is Adventure Game Studio, but I haven't used it much yet, just watched a couple tutorials on youtube. But it's a point-and-click only engine as it seems so it won't be of much help for this type of game, unless I get really creative with my controls (I'll keep this engine in mind for other possible projects in the future, though).
      I've tried Godot as well, which seems to be really hard to learn for a beginner of my level, especially as the coding language is completely unique to the engine from what I've read (and noticed myself).
      I did come across Unity and UE (Unreal Engine) and from what I've read it seems that Unity is better, but, again, I understand very little of any reviews I've read. What's mostly scaring me away is that services that have Premium possibilities you pay for are usually really limited in a stupid way. But if this is not the case, hey, let me know!
      Pixel-art-ish animation would work well, too, so an alternative to RPG Maker would be fine (or at the very least a cheap alternative where I don't have to pay monthly for).
      The art for the game I can provide and create completely by myself if it's 2D. I'm an artist mostly and I have experience with making comics and digital drawings (fanart mostly hahaha) and I've gotten into animation which I'm fairly decent at (I'd be willing to learn 3D animation, though!).
      So, that's about all the info I think might be of importance, but if there's anything more you need to know to help me, I'll answer as quick as I can!! And if you tell me I gotta give up on some of the features I want the game to have, I'd be willing to listen to suggestions. 
      Thanks in advance to everyone who is willing to help me!
    • By Hashbrown
      I'm wondering what is the right way to create level collision for a very basic level like the following image (click on it for a larger version):

      I'm not  what to search, so I'm a little confused. What I'm thinking is AABB collision tests for the cubes and walls, maybe keeping them all in arrays, and checking the array for collisions every frame. Again, not sure if that's the correct way of doing this.  
      I'm also not sure about the platform in the middle since the character would have to go up a slope like this one: 

      ...and stand on the platform. The floor is set at y:0 at the moment, but it might be higher or lower in different parts of the map. If anybody has links I can read to learn, or even just keywords I can use to search. I'd really appreciate it. I just don't know where to start in terms of searching. Thanks!  
      Edit: I don't plan on using collider shapes outside of cubes and that slope in green. Making sure to keep the collision very simple. I don't think any of these level colliders are going to rotate either, so it's going to be axis aligned. 
      Edit 2:  I just found this old post from 2002 and from what I understand in one of the answers:  divide the world in different cubes and each one holds a list of all the aabb colliders within that particular cube. I'm guessing in order to avoid having to walk and test so many colliders. Not sure if I'm on the right track though. Also need to figure out how to go up the slope, obb perhaps?
    • By vvvvv
      oh boy howdy howdy
      i know little to nothing about game design and programming but i am a seasoned artist and am a huge gamer always have been
      i recently got a very small taste of the industry if you can even call it that from the last UE4 game jam i helped with voice acting concept art writing and vector art
      i absolutely loved it and am already itching to learn and do more but??? i have no idea how to go about it
      the person i was working with during the game jam is years ahead of me and is already looking into getting me into some contract work and teaching me 3d modeling/painting/sculpting but at the moment hes currently busy with making a game for RTX!
      while hes busy i thought id delve into some forums and get my feet wet 
      any info or tips on how or where to get started would be amazing thanks!
  • Advertisement
  • Popular Now

  • Forum Statistics

    • Total Topics
      631354
    • Total Posts
      2999503
×

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!