OpenTTD Source 20250524-master-gc366e6a48e
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 <http://www.gnu.org/licenses/>.
6 */
7
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
33NewGRFProfiler::NewGRFProfiler(const GRFFile *grffile) : grffile(grffile)
34{
35}
36
43
49{
50 using namespace std::chrono;
51 this->cur_call.root_sprite = resolver.root_spritegroup->nfo_line;
52 this->cur_call.subs = 0;
53 this->cur_call.time = (uint32_t)time_point_cast<microseconds>(high_resolution_clock::now()).time_since_epoch().count();
55 this->cur_call.cb = resolver.callback;
56 this->cur_call.feat = resolver.GetFeature();
57 this->cur_call.item = resolver.GetDebugID();
58}
59
64{
65 using namespace std::chrono;
66 this->cur_call.time = (uint32_t)time_point_cast<microseconds>(high_resolution_clock::now()).time_since_epoch().count() - this->cur_call.time;
67
68 struct visitor {
69 uint32_t operator()(std::monostate)
70 {
71 return 0;
72 }
73 uint32_t operator()(CallbackResult cb_result)
74 {
75 return cb_result;
76 }
77 uint32_t operator()(const SpriteGroup *group)
78 {
79 if (group == nullptr) return 0;
80 if (group->type != SGT_RESULT) return group->nfo_line;
81 return GetSpriteLocalID(static_cast<const ResultSpriteGroup *>(group)->sprite);
82 }
83 };
84 this->cur_call.result = std::visit(visitor{}, result);
85
86 this->calls.push_back(this->cur_call);
87}
88
93{
94 this->cur_call.subs += 1;
95}
96
97void NewGRFProfiler::Start()
98{
99 this->Abort();
100 this->active = true;
102}
103
104uint32_t NewGRFProfiler::Finish()
105{
106 if (!this->active) return 0;
107
108 if (this->calls.empty()) {
109 IConsolePrint(CC_DEBUG, "Finished profile of NewGRF [{:08X}], no events collected, not writing a file.", std::byteswap(this->grffile->grfid));
110
111 this->Abort();
112 return 0;
113 }
114
115 std::string filename = this->GetOutputFilename();
116 IConsolePrint(CC_DEBUG, "Finished profile of NewGRF [{:08X}], writing {} events to '{}'.", std::byteswap(this->grffile->grfid), this->calls.size(), filename);
117
118 uint32_t total_microseconds = 0;
119
120 auto f = FioFOpenFile(filename, "wt", Subdirectory::NO_DIRECTORY);
121
122 if (!f.has_value()) {
123 IConsolePrint(CC_ERROR, "Failed to open '{}' for writing.", filename);
124 } else {
125 fmt::print(*f, "Tick,Sprite,Feature,Item,CallbackID,Microseconds,Depth,Result\n");
126 for (const Call &c : this->calls) {
127 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);
128 total_microseconds += c.time;
129 }
130 }
131
132 this->Abort();
133 return total_microseconds;
134}
135
136void NewGRFProfiler::Abort()
137{
138 this->active = false;
139 this->calls.clear();
140}
141
147{
148 return fmt::format("{}grfprofile-{:%Y%m%d-%H%M}-{:08X}.csv", FiosGetScreenshotDir(), fmt::localtime(time(nullptr)), std::byteswap(this->grffile->grfid));
149}
150
151/* static */ uint32_t NewGRFProfiler::FinishAll()
152{
154
155 uint64_t max_ticks = 0;
156 uint32_t total_microseconds = 0;
157 for (NewGRFProfiler &pr : _newgrf_profilers) {
158 if (pr.active) {
159 total_microseconds += pr.Finish();
160 max_ticks = std::max(max_ticks, TimerGameTick::counter - pr.start_tick);
161 }
162 }
163
164 if (total_microseconds > 0 && max_ticks > 0) {
165 IConsolePrint(CC_DEBUG, "Total NewGRF callback processing: {} microseconds over {} ticks.", total_microseconds, max_ticks);
166 }
167
168 return total_microseconds;
169}
170
175{
176 NewGRFProfiler::FinishAll();
177});
178
182/* static */ void NewGRFProfiler::StartTimer(uint64_t ticks)
183{
185}
186
190/* static */ void NewGRFProfiler::AbortTimer()
191{
193}
A timeout timer will fire once after the interval.
Definition timer.h:116
void Reset()
Reset the timer, so it will fire again after the timeout.
Definition timer.h:140
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(TextColour 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:90
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:242
Functions for Standard In/Out file operations.
std::string_view FiosGetScreenshotDir()
Get the directory for screenshots.
Definition fios.cpp:591
@ NO_DIRECTORY
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 SpriteGroup * > 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.
Functions related to low-level strings.
Dynamic data of a loaded NewGRF.
Definition newgrf.h:115
GrfSpecFeature feat
GRF feature being resolved for.
uint32_t time
Time taken for resolution (microseconds)
uint32_t subs
Sub-calls to other sprite groups.
uint64_t tick
Game tick.
uint32_t root_sprite
Pseudo-sprite index in GRF file.
CallbackID cb
Callback ID.
uint32_t item
Local ID of item being resolved for.
uint32_t result
Result of callback.
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.
~NewGRFProfiler()
Complete profiling session and write data to file.
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.
Definition of Interval and OneShot timers.
Definition of the tick-based game-timer.