[RGSS3] Why is my FPS so low after disabling event and sprite updating

Here is my code for disabling all events and character sprites from updating.

I create 5000 copies of an event for testing performance.

Spoiler
class Game_Map # Copy the first event a bunch of times alias :tester_setup_events :setup_events def setup_events tester_setup_events ev = @map.events[1] 5000.times {|i| new_ev = Game_Event.new(i+2, ev) ev.x = rand(width) ev.y = rand(height) @events[i+2] = new_ev } endendclass Game_Map def update_events #@events.each_value {|event| event.update } #@common_events.each {|event| event.update end def setup_starting_map_event #event = @events.values.find {|event| event.starting } # Oops #event.clear_starting_flag if event #@interpreter.setup(event.list, event.id) if event #event endendclass Sprite_Character def update endendclass Game_Event def update endendclass Spriteset_Map def update_characters endend
Here are some test results. They are not meant to be taken as hard numbers, but you can see that even after disabling things, the performance is still not the same as there being no events at all.

JRXlbau.jpg


I don't understand what is causing my FPS to drop to 10 even after I've explicitly made it so that the engine no longer loops over 5000 sprites and 5000 events.

What is the cause of this?

Some additional cases that are not included in the results above.

They assume all the modifiers have been applied.

Viewport updating: 5000 events at 20 FPS (compared to 10)

Spoiler
class Spriteset_Map

def update_viewports

end

end
maybe just the sheer number of data in that map even if most of it doesn't do anything...


Also, I think Game_Player might still be looping at those 5000 events for triggers...
But let's say your map had one event, but then you added an array of a billion integers. It doesn't cause a problem. Let's say you had an array of a billion RPG::Event objects (they don't get updated. They're just there). Having "data" lying around doesn't cause problems (it might cause memory problems, which might lead to performance issues at some point like if the process needs to start swapping memory to disk or something), it's when you need to put effort into processing it.

Having 10 parallel processes that do "nothing" already kills FPS from 120 to like 60.

You're right, I missed a method in game map

def update_interpreter loop do @interpreter.update return if @interpreter.running? if @interpreter.event_id > 0 unlock_event(@interpreter.event_id) @interpreter.clear end return unless setup_starting_event end end def setup_starting_event refresh if @need_refresh return true if @interpreter.setup_reserved_common_event return true if setup_starting_map_event return true if setup_autorun_common_event return false end def setup_starting_map_event event = @events.values.find {|event| event.starting } # Oops event.clear_starting_flag if event @interpreter.setup(event.list, event.id) if event event endHowever, taking it out didn't make a real difference (maybe 1 FPS boost)I added a little print statement to the `events` reader and no one's trying to access it.

I've checked that all references to @events within Game_Map were not trying to iterate it.

My FPS is still the same as what I recorded in the spreadsheet.

I wish there was a way to monitor the game's execution and benchmark all of the methods to see what's being called the most and how much time each call takes...

EDIT:

Here's another one: viewports.

5000 sprites get created and assigned to a viewport.

When the viewport updates, it presumably also updates those objects.

When I take out viewport updating, 5000 events averages 20 FPS, which is much better than 10 at least!

class Spriteset_Map def update_viewports endendThis is...somewhat better...but still, I can expect at least 100 FPS right?Ideally, if I don't want an event to update, I want it to be completely gone from the update loop .

I suspect Graphics.update might be part of the reason, but there's probably nothing much I can do there.
Why? Because Spriteset_Map creates a sprite for each character on the map and you have 5000 events there.
the thing is, it shouldn't lag once they are already made, unless they're getting updated/iterated... so something would still be running thru them it seems...
Oh, I get what you mean. Similar thing happens with Plane and Viewport, the latter being responsable for the most notorious drop in FPS.
she also removed viewport updates... so maybe something hidden like Graphics.whatever is still looping thru them... or having that amount of data just really makes it lag...
Plane updating definitely seems to be an issue as well, seeing how taking out the parallax showed some results at 1000 events (80 FPS vs 70 FPS). It didn't do anything with 5000 events though.

So I thought, why not just take out the entire map sprite update!

class Spriteset_Map def update endendAt 5000 events, that bumped it up to 22 FPS.But...wouldn't this suggest that viewports and planes are just a minor part of it?

Ignoring events for now, something that I decided to try out:

class Game_Map # Copy the first event a bunch of times alias :tester_setup_events :setup_events def setup_events tester_setup_events @sprites = [] 5000.times {|i| @sprites.push(Sprite.new) } endendclass Sprite def update endendThis...pretty much killed FPS.So, creating a sprite, even if you're not doing anything with it, causes issues.

Lemony would be right then; I created 5000 sprites, and that's the source of the problem.
The mere presence of viewports/sprites/planes is detrimental to the FPS. 

stuff = []5000.times {stuff << Viewport.new}loop doGraphics.updateInput.updateendCheck your FPS there, and then change Viewport for Sprite, and then for Plane.
yeah, the power to handle those data alone seems to be quite a bit much
Realistically, we wouldn't be creating more than 10-20 planes or viewports

However, sprites are created very often, even if it's for something really trivial.

One idea is to dispose sprites that do not need to be held onto. For example, you have an event on the other side of the map that you're not going to see; no point in having a sprite for it.

If you're going to dispose 5000 sprites at once, you're going to experience notice-able lag.

Code:
def run(n)    t1 = Time.now  sprites = []  n.times {sprites.push(Sprite.new) }  t2 = Time.now   t3 = Time.now  n.times {|i| sprites[i].dispose }  t4 = Time.now  return "%d - Create: %f, Dispose: %f" %[n, t2 - t1, t4 - t3]endf = File.new("test.txt", 'wb')  f.write(run(10) +"\n")  f.write(run(100) +"\n")  f.write(run(500) +"\n")  f.write(run(1000) +"\n")  f.write(run(10000) +"\n")f.close
However, for smaller amounts, it's more reasonable

Code:
10 - Create: 0.000000, Dispose: 0.000000100 - Create: 0.001000, Dispose: 0.000000500 - Create: 0.005000, Dispose: 0.0070001000 - Create: 0.034000, Dispose: 0.02900010000 - Create: 0.232000, Dispose: 2.838000
So let's say you're disposing 500 sprites every frame because you are suddenly teleporting from one point to another every frame. It doesn't seem to be too bad for reasonable amounts of events (which are typically the major source of sprite creation)
Graphics.update does have to consider every non-freed drawable object in existence, even ones currently marked not visible and Sprites which contain no bitmap (and viewports that contain no sprites, etc), and including if the screen is currently frozen. I've pretty much taken this as a given for a while now. I did my own similar bench tests a while back that identified sprites as the bottleneck but I never pushed it quite that far as far as pure creating/disposing sprites. I'm glad you did, because it reveals an important piece of information.

Those numbers suggest that time cost of disposal/sprite increases as the total amount of unfreed sprites also increases. I slightly modified that for a few more tests:

def run(n) GC.disable t1 = Time.now sprites = [] n.times { |i| sprites = Sprite.new } t2 = Time.now t3 = Time.now n.times { |i| sprites.dispose } t4 = Time.now t5 = Time.now n.times { Sprite.new.dispose } t6 = Time.now t7 = Time.now sprites.clear GC.enable GC.start t8 = Time.now return "%d - Create: %f, Dispose: %f, Both: %f, GC: %f" %[n, t2 - t1, t4 - t3, t6 - t5, t8 - t7]endf = File.new("test.txt", 'wb') f.write(run(10) +"\n") f.write(run(100) +"\n") f.write(run(500) +"\n") f.write(run(1000) +"\n") f.write(run(10000) +"\n")f.closeI noted the time to both create and dispose a sprite is barely above what it takes to create alone, so the individual disposal cost is not that high. However, if you comment out the first line which does the group disposal in the above, you'll notice the time it takes to dispose the individual sprites shoots way up. So the time it takes to dispose a sprite has direct correlation to how many currently exist.I also parsed out GC in the above, because in any real-world situation you have GC constantly working to recycle those sprites that you are disposing once they lose references. Similarly, it looks like GC time increases exponentially the more sprites currently exist and need to be collected at any one time, whereas other orphaned objects have little impact at all.

All this together suggests there may be a bottleneck in accessing the metadata of these types of objects correlated to how many currently exist. There isn't much we can do about it through Ruby, but it does help to formulate strategies for how to workaround the issue.

Bitmaps I have tested before to be very slow when GC'd, but that may have been related to memory while sprite objects have very low impact on memory overall, so the probably is likely elsewhere. GC appears only slightly slower on sprites that are not freed, but it is not a good idea to orphan sprites you have not disposed (anyone not familiar, see my sig. thread link re: game.exe crashes caused by GC interaction with undisposed sprites associated with disposed viewports)

Iteration is still a huge chunk of that processing time in any reasonable real world scenario, though. The last time I worked on something similar to this was for VX, which had slower processing of many basic commands with Ruby 1.8.6, and adding overhead to manage sprites generally wasn't worth the effort unless the user was going overboard with the sprites, unless you were going to restructure the code altogether to significantly reduce iteration.
Thanks for checking the sprite issue more closely.


Most of the sprites that are created in-game are for events or animations.


5000 events is likely an unrealistic amount.


Even 1000 events is pushing it.


I don't really see why someone would need to have a dozen animations going on concurrently at all times either.


I've never created a full AAA RM game so I don't know whether they need 10000 events or not running at the same time but game quality is not measured by how many things you throw at it (though, good graphics may require a lot of things going on)


Maybe there are people that need 5000 events on the map because they just want to have a 500x500 "world map". Compared to 250000 tiles, that's a relatively small amount of events.


Optimizing for 500 events can be done by just disabling sprite updates and event updates. Sprite updates can be ignored safely because, well, if you don't see it on the screen, why does it need to update anyways? In some 2.5D or 3D games, they wouldn't even bother rendering anything that's behind a wall if you can't see past it.


Event updates should be managed very carefully, because we can already see that the decision to make autonomous movement stop when the event is not "near the screen" is already causing a lot of headache. That really should be given the option to enable or disable on a per-event or per-event-page basis, which can be easily added of course using scripts and event comments.


My machine is pretty average, and if I'm pushing out 90 FPS at 500 events compared to 15, it should be "good enough" in terms of playability.
I think Engr. Shana had a good point about the player still looking at all of those events on each frame.


If you RE-enable the event and sprite updates, I suspect your game might slow down a great deal.


Game_Player has the check_event_here and check_event_there methods that call a Game_Map method event_at (I'm not positive those are the correct names, as I'm on my work PC). That method loops through every event until it finds one at the player's location. Maybe making THAT method (and any like it) not do anything, might give you some different results.
Maybe there are people that need 5000 events on the map because they just want to have a 500x500 "world map". Compared to 250000 tiles, that's a relatively small amount of events.
Except the bottleneck is not with the tiles themselves. In comparison to Sprites, the tilemap class is actually very efficient. Increasing my 13 x 17 map to 2000 by 2000 (by manipulating the data table before tilemap is created) offers no noticeable drop in framerate. This is likely because we only have a single Ruby handler for this object (plus one for each of the bitmaps it is constructed from). Sprites have one Ruby handler each, and have shown performance drops at a geometric rate past a certain point.

Optimizing for 500 events can be done by just disabling sprite updates and event updates. Sprite updates can be ignored safely because, well, if you don't see it on the screen, why does it need to update anyways? In some 2.5D or 3D games, they wouldn't even bother rendering anything that's behind a wall if you can't see past it.


Event updates should be managed very carefully, because we can already see that the decision to make autonomous movement stop when the event is not "near the screen" is already causing a lot of headache. That really should be given the option to enable or disable on a per-event or per-event-page basis, which can be easily added of course using scripts and event comments.
Every anti-lag script I have ever seen is constructed like this. The general strategy is to not update things that don't need to be updated because they are off screen. The overhead is that at least some calculation needs to be done to determine if near_the_screen? (usually determined either each frame, or on the fly). If you are in a large map where most of the events are spread out, great, otherwise, you won't see much of a difference.


I've also seen the comment tag thing to determine if the event should be updated or not. I've seen some that add tags that prevent sprite association (for graphicless autoruns) or event updates (for background style sprites that never move). This works great with little overhead, but it also requires much more setup.


There is room for optimization in the way that events are handled and also within the update methods themselves. When I did some tests in VX a while back, I the update and all associated Sprite_Character methods using pretty much the same structure but only got about 5-10% performance increase for maps that were already running at < 30 FPS for me. There is much, much more sloppy iteration in Game_Map that would take some heavy provisioning or rewrites to get around.


Basically, if you are going to use 1000+ events on any one map the creator should probably rethink how they are doing things. Even 500 events is pushing it, really, but sprites in general are used frequently both by the base scripts and many scripters. Even just counting the map screen, you have to consider weather, pictures, the timer, all the character sprites, any animation playing on any one of the characters, shadow, as well as the Tilemap, Plane, 3 Viewports, and the message windows which are all operating on similar bottlenecks. The code for this is much improved in ACE over VX in regard to weather, pictures, and animations, but character sprites are pretty much the same (granted, with a much better method layout). They are set up for maximum flexibility, not speed, you could, say, trivially show a balloon over your airship if you wanted.


This computer quickly drops in framerate due to event bloat at far less than 100 events, though, and given that I am still well within the system requirements for RPG Maker VX ACE, discussion on the matter is always useful to make more games playable by a broader audience.


@Shaz-


events_xy is I believe the method that you are referring to. There is an optimized version of this in ACE used for referencing events on a tile through the interpreter, and events_xy is only used by Game_Player to check for events and trigger one. For events, the event simply checks if the player is in the spot they are checking. It isn't optimized, but it's not exactly a bottleneck in this instance. There are other, similar methods to determine where things are for collision that also iterate over every single event, and those are done on any collision test.
Well since you guys are talking about performance and things like that, something different I did in my anti-lag is having a frame skipper.

I actually didn't think it would make much difference in the performance, but it does, and a lot, for example, Rpg Maker 2k runs at 30FPS, but it isn't felt that much, but when Ace drops to 30FPS it gets really laggy, so by fixing the Frames to 30, it made at least for my tests really smoother the game.

So an extra idea to optimize that is having a benchmark method to calculate the frames, and then activate a frame skipper according to the results. I know maybe I went a little off-topic about the sprites, but by fixing a FPS a little above what your getting which is a little over 20, maybe you can have much better results.
@Raizen -

Yeah, I completely forgot about frameskippers. Here is a simple one:

Spoiler
class << Graphics @@__count = 0 @@__increment = 0 alias frameskip_update update def update @@__count += 1 if @@__count >= @@__frameskip @@__count -= @@__frameskip frameskip_update end end alias frset frame_rate= def frame_rate=(fr) @@__frameskip = 60.0 / fr frset(fr) end alias fadeout_ext_fr fadeout def fadeout(duration) duration /= @@__frameskip fadeout_ext_fr(duration) end alias fadein_ext_fr fadeout def fadein(duration) duration /= @@__frameskip fadein_ext_fr(duration) end alias transition_ext_fr transition def transition(*args) args[0] = 10 unless args[0] args[0] /= @@__frameskip transition_ext_fr(*args) end end
I have had slightly smoother gameplay when testing fixed frameskippers on projects that were already running at only slightly reduced FPS. Remember, even if you skip the frame update, all the other iteration has to be done in the background. Once the framerate is already < 30 due to bloat, I stop seeing any noticeable performace gain from skipping and once at < 20 or so it is actually detrimental (because the path between each Graphics update at that point is likely longer than the time it actually takes to redraw the screen, unless we are talking huge bloat from sprites from unrealistic situations described above). Reducing framerate also does noticeably reduce quality (60 to 30, even) for any instance where the project is actually running correctly and any reduction that cannot be divided evenly looks slightly "off" because every single sprite/animation made to look good at 60 FPS. Overall, however, it shows the biggest performance boost vs the other methods I mentioned, albeit for a narrower range of people.

The problem with making it variable based on benchmarks, though, is that the Graphics module is far better at timing than any calculation I can perform with Time (this is system dependent, I can only increment detect increments of ~ 0.015625 seconds) and frames should be precisely timed for smooth gameplay. A single update takes approximately abs.((frame_rate / 60) - (time to draw screen + time since last update)) seconds. You can calculate optimal frame time and time since last update easily enough, but not how long the screen draw will actually take, which can very greatly depending on the circumstances. This lack of reliability also makes it impossible to determine the actual amount of time Graphics.update is actually taking on a given system.

The whole engine, from using Ruby as a code base down to the way Graphics are handled is built for flexibility, not speed. Even though Sprite is the simplest object you can use to display any one bitmap in RGSSx, each one is still its own layer supporting independent movement, transparency, scaling, blend, rotation, wave effects, and real time color or tone changing without altering the bitmap. The only real solution to slowdown from sprite usage is to use less sprites. 500 events doesn't have to mean 500 sprites.
The only real solution to slowdown from sprite usage is to use less sprites. 500 events doesn't have to mean 500 sprites.
That's a good point.


For example, transfer events are very common, and they usually have no graphic associated with it.


However, the engine will not care about this and simply create a sprite for it, despite it being completely unnecessary.


Of course, the idea is that if you suddenly do a page switch and now you need a sprite...what then? Create a new sprite as needed? That works, I don't see why not. As you have shown, sprite creation (and sprite disposal) are sufficiently fast for small amounts.


Another obvious problem is sprite updating...when there is no image!


If you don't have a bitmap, you don't need to update the sprite. I think that is a reasonable assumption.


So when someone asks why their world map lags so much...well, it probably has something to do with having 100 transfer events.
Of course, the idea is that if you suddenly do a page switch and now you need a sprite...what then? Create a new sprite as needed? That works, I don't see why not. As you have shown, sprite creation (and sprite disposal) are sufficiently fast for small amounts.
Yes, that is exactly what I was suggesting. Spriteset is supposed to manage all the associated sprites for a scene, after all. Instead of creating them all at once and iterating through the sprites, we can iterate through objects that potentially need a sprite and create a sprite as needed. The main concerns are:


1. Minimize the overhead of this algorithm. Since it is performing extra check, there are situations where it may slow you down instead of the opposite.


2. Individual sprite disposal is shown to be fairly quick if you aren't already bottlenecked by having too many sprites, but I never tested the effects of rapidly disposing sprites every frame while the game is already running. When the picture bug existed at engine release (any erased picture would constantly create and orphan a 16x16 blank bitmap every frame without disposal), everything would stutter at roughly about 20 GC'd bitmaps/frame (for me anyway). The benchmark for me with no outside variables shows a minimal (eg., ~ 0.015625 since my clock loses precision at that point) latency for switching on GC with up to 500 sprites created/disposed individually, which would probably be minimized if GC was running the entire time. However, everything doesn't halt just because the GC is running, and it is only given priority in certain situations. If you are discarding a ton of sprites, eventually it will need to 'catch up' and cause stuttering. Manually invoking GC.start at a point before it becomes backed up is one solution (since the GC time also raises geometrically based on how many sprites are to be GC'd), but it is itself a costly operation so careful consideration is needed there. If you are tightly managing the creation and disposal of sprites, anyway, you should never be dealing with more than ~30 at any given time, and there should hopefully be no situation where you need to create and dispose so many every single frame to the point GC would fall behind.

Original thread: https://forums.rpgmakerweb.com/threads/rgss3-why-is-my-fps-so-low-after-disabling-event-and-sprite-updating.22684/