OpenTTD Source 20261112-master-gbcbec5e63f
newgrf_profiling.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "stdafx.h"
11
12#include "newgrf_profiling.h"
13#include "fileio_func.h"
14#include "string_func.h"
15#include "console_func.h"
16#include "spritecache.h"
17#include "3rdparty/fmt/chrono.h"
18#include "timer/timer.h"
20
21#include <chrono>
22
23#include "safeguards.h"
24
25std::vector<NewGRFProfiler> _newgrf_profilers;
26
27
35
41{
42 using namespace std::chrono;
43 this->cur_call.root_sprite = resolver.root_spritegroup->nfo_line;
44 this->cur_call.subs = 0;
45 this->cur_call.time = (uint32_t)time_point_cast<microseconds>(high_resolution_clock::now()).time_since_epoch().count();
47 this->cur_call.cb = resolver.callback;
48 this->cur_call.feat = resolver.GetFeature();
49 this->cur_call.item = resolver.GetDebugID();
50}
51
57{
58 using namespace std::chrono;
59 this->cur_call.time = (uint32_t)time_point_cast<microseconds>(high_resolution_clock::now()).time_since_epoch().count() - this->cur_call.time;
60
61 struct visitor {
62 uint32_t operator()(std::monostate)
63 {
64 return 0;
65 }
66 uint32_t operator()(CallbackResult cb_result)
67 {
68 return cb_result;
69 }
70 uint32_t operator()(const ResultSpriteGroup *group)
71 {
72 return group == nullptr ? 0 : GetSpriteLocalID(group->sprite);
73 }
74 uint32_t operator()(const TileLayoutSpriteGroup *group)
75 {
76 return group == nullptr ? 0 : group->nfo_line;
77 }
78 uint32_t operator()(const IndustryProductionSpriteGroup *group)
79 {
80 return group == nullptr ? 0 : group->nfo_line;
81 }
82 };
83 this->cur_call.result = std::visit(visitor{}, result);
84
85 this->calls.push_back(this->cur_call);
86}
87
92{
93 this->cur_call.subs += 1;
94}
95
96void NewGRFProfiler::Start()
97{
98 this->Abort();
99 this->active = true;
101}
102
103uint32_t NewGRFProfiler::Finish()
104{
105 if (!this->active) return 0;
106
107 if (this->calls.empty()) {
108 IConsolePrint(CC_DEBUG, "Finished profile of NewGRF [{}], no events collected, not writing a file.", FormatArrayAsHex(this->grffile->grfid));
109
110 this->Abort();
111 return 0;
112 }
113
114 std::string filename = this->GetOutputFilename();
115 IConsolePrint(CC_DEBUG, "Finished profile of NewGRF [{}], writing {} events to '{}'.", FormatArrayAsHex(this->grffile->grfid), this->calls.size(), filename);
116
117 uint32_t total_microseconds = 0;
118
119 auto f = FioFOpenFile(filename, "wt", Subdirectory::None);
120
121 if (!f.has_value()) {
122 IConsolePrint(CC_ERROR, "Failed to open '{}' for writing.", filename);
123 } else {
124 fmt::print(*f, "Tick,Sprite,Feature,Item,CallbackID,Microseconds,Depth,Result\n");
125 for (const Call &c : this->calls) {
126 fmt::print(*f, "{},{},0x{:X},{},0x{:X},{},{},{}\n", c.tick, c.root_sprite, c.feat, c.item, (uint)c.cb, c.time, c.subs, c.result);
127 total_microseconds += c.time;
128 }
129 }
130
131 this->Abort();
132 return total_microseconds;
133}
134
135void NewGRFProfiler::Abort()
136{
137 this->active = false;
138 this->calls.clear();
139}
140
146{
147 return fmt::format("{}grfprofile-{:%Y%m%d-%H%M}-{}.csv", FiosGetScreenshotDir(), fmt::localtime(time(nullptr)), FormatArrayAsHex(this->grffile->grfid));
148}
149
150/* static */ uint32_t NewGRFProfiler::FinishAll()
151{
153
154 uint64_t max_ticks = 0;
155 uint32_t total_microseconds = 0;
156 for (NewGRFProfiler &pr : _newgrf_profilers) {
157 if (pr.active) {
158 total_microseconds += pr.Finish();
159 max_ticks = std::max(max_ticks, TimerGameTick::counter - pr.start_tick);
160 }
161 }
162
163 if (total_microseconds > 0 && max_ticks > 0) {
164 IConsolePrint(CC_DEBUG, "Total NewGRF callback processing: {} microseconds over {} ticks.", total_microseconds, max_ticks);
165 }
166
167 return total_microseconds;
168}
169
174{
175 NewGRFProfiler::FinishAll();
176});
177
182/* static */ void NewGRFProfiler::StartTimer(uint64_t ticks)
183{
184 _profiling_finish_timeout.Reset({ TimerGameTick::Priority::None, static_cast<uint>(ticks) });
185}
186
190/* static */ void NewGRFProfiler::AbortTimer()
191{
193}
A timeout timer will fire once after the interval.
Definition timer.h:116
static TickCounter counter
Monotonic counter, in ticks, since start of game.
@ None
These timers can be executed in any order; the order is not relevant.
void IConsolePrint(ExtendedTextColour colour_code, const std::string &string)
Handle the printing of text entered into the console or redirected there by any other means.
Definition console.cpp:91
Console functions used outside of the console code.
static const TextColour CC_DEBUG
Colour for debug output.
static const TextColour CC_ERROR
Colour for error lines.
std::optional< FileHandle > FioFOpenFile(std::string_view filename, std::string_view mode, Subdirectory subdir, size_t *filesize)
Opens a OpenTTD file somewhere in a personal or global directory.
Definition fileio.cpp:248
Functions for standard in/out file operations.
std::string_view FiosGetScreenshotDir()
Get the directory for screenshots.
Definition fios.cpp:602
@ None
A path without any base directory.
static TimeoutTimer< TimerGameTick > _profiling_finish_timeout({ TimerGameTick::Priority::None, 0 }, []() { NewGRFProfiler::FinishAll();})
Check whether profiling is active and should be finished.
Profiling of NewGRF action 2 handling.
std::variant< std::monostate, CallbackResult, const ResultSpriteGroup *, const TileLayoutSpriteGroup *, const IndustryProductionSpriteGroup * > ResolverResult
Result of resolving sprite groups:
A number of safeguards to prevent using unsafe methods.
uint32_t GetSpriteLocalID(SpriteID sprite)
Get the GRF-local sprite id of a given sprite.
Functions to cache sprites in memory.
Definition of base types and functions in a cross-platform compatible way.
std::string FormatArrayAsHex(std::span< const uint8_t > data)
Format a byte array into a continuous hex string.
Definition string.cpp:76
Functions related to low-level strings.
Dynamic data of a loaded NewGRF.
Definition newgrf.h:126
Measurement of a single sprite group resolution.
Callback profiler for NewGRF development.
void RecursiveResolve()
Capture a recursive sprite group resolution.
static void StartTimer(uint64_t ticks)
Start the timeout timer that will finish all profiling sessions.
void EndResolve(const ResolverResult &result)
Capture the completion of a sprite group resolution.
Call cur_call
Data for current call in progress.
bool active
Is this profiler collecting data.
const GRFFile * grffile
Which GRF is being profiled.
uint64_t start_tick
Tick number this profiler was started on.
static void AbortTimer()
Abort the timeout timer, so the timer callback is never called.
void BeginResolve(const ResolverObject &resolver)
Capture the start of a sprite group resolution.
NewGRFProfiler(const GRFFile *grffile)
Create profiler object and begin profiling session.
std::vector< Call > calls
All calls collected so far.
std::string GetOutputFilename() const
Get name of the file that will be written.
Interface for SpriteGroup-s to access the gamestate.
virtual uint32_t GetDebugID() const
Get an identifier for the item being resolved.
CallbackID callback
Callback being resolved.
virtual GrfSpecFeature GetFeature() const
Get the feature number being resolved for.
const SpriteGroup * root_spritegroup
Root SpriteGroup to use for resolving.
A result sprite group returns the first SpriteID and the number of sprites in the set.
Action 2 sprite layout for houses, industry tiles, objects and airport tiles.
Definition of Interval and OneShot timers.
Definition of the tick-based game-timer.