yaze 0.3.2
Link to the Past ROM Editor
 
Loading...
Searching...
No Matches
performance_profiler.cc
Go to the documentation of this file.
2
3#include <algorithm>
4#include <iomanip>
5#include <iostream>
6#include <numeric>
7#include <sstream>
8
10#include "util/log.h"
11
12namespace yaze {
13namespace gfx {
14
16 static PerformanceProfiler instance;
17 return instance;
18}
19
21 : enabled_(true), is_shutting_down_(false) {
22 // Initialize with memory pool for efficient data storage
23 // Reserve space for common operations to avoid reallocations
24 active_timers_.reserve(50);
25 operation_times_.reserve(100);
26 operation_totals_.reserve(100);
27 operation_counts_.reserve(100);
28
29 // Register destructor to set shutdown flag
30 std::atexit([]() { Get().is_shutting_down_ = true; });
31}
32
33void PerformanceProfiler::StartTimer(const std::string& operation_name) {
35 return;
36
37 active_timers_[operation_name] = std::chrono::high_resolution_clock::now();
38}
39
40void PerformanceProfiler::EndTimer(const std::string& operation_name) {
42 return;
43
44 auto timer_iter = active_timers_.find(operation_name);
45 if (timer_iter == active_timers_.end()) {
46 // During shutdown, silently ignore missing timers to avoid log spam
47 return;
48 }
49
50 auto end_time = std::chrono::high_resolution_clock::now();
51 auto duration = std::chrono::duration_cast<std::chrono::microseconds>(
52 end_time - timer_iter->second)
53 .count();
54
55 double duration_ms = duration / 1000.0;
56
57 // Store timing data using memory pool for efficiency
58 operation_times_[operation_name].push_back(static_cast<double>(duration));
59 operation_totals_[operation_name] += duration_ms;
60 operation_counts_[operation_name]++;
61
62 active_timers_.erase(timer_iter);
63}
64
66 const std::string& operation_name) const {
67 TimingStats stats;
68
69 auto times_iter = operation_times_.find(operation_name);
70 auto total_iter = operation_totals_.find(operation_name);
71
72 if (times_iter == operation_times_.end() || times_iter->second.empty()) {
73 return stats;
74 }
75
76 const auto& times = times_iter->second;
77 stats.sample_count = times.size();
78 stats.total_time_ms =
79 (total_iter != operation_totals_.end()) ? total_iter->second : 0.0;
80
81 if (times.empty()) {
82 return stats;
83 }
84
85 // Calculate min, max, and average
86 stats.min_time_us = *std::min_element(times.begin(), times.end());
87 stats.max_time_us = *std::max_element(times.begin(), times.end());
88 stats.avg_time_us =
89 std::accumulate(times.begin(), times.end(), 0.0) / times.size();
90
91 // Calculate median
92 std::vector<double> sorted_times = times;
93 std::sort(sorted_times.begin(), sorted_times.end());
95
96 return stats;
97}
98
99std::string PerformanceProfiler::GenerateReport(bool log_to_sdl) const {
100 std::ostringstream report;
101 report << "\n=== YAZE Unified Performance Report ===\n";
102 report << "Total Operations Tracked: " << operation_times_.size() << "\n";
103 report << "Performance Monitoring: " << (enabled_ ? "ENABLED" : "DISABLED")
104 << "\n\n";
105
106 // Memory pool statistics
107 auto [used_bytes, total_bytes] = MemoryPool::Get().GetMemoryStats();
108 report << "Memory Pool Usage: " << std::fixed << std::setprecision(2)
109 << (used_bytes / (1024.0 * 1024.0)) << " MB / "
110 << (total_bytes / (1024.0 * 1024.0)) << " MB\n\n";
111
112 for (const auto& [operation, times] : operation_times_) {
113 if (times.empty())
114 continue;
115
116 auto stats = GetStats(operation);
117 report << "Operation: " << operation << "\n";
118 report << " Samples: " << stats.sample_count << "\n";
119 report << " Min: " << std::fixed << std::setprecision(2)
120 << stats.min_time_us << " μs\n";
121 report << " Max: " << std::fixed << std::setprecision(2)
122 << stats.max_time_us << " μs\n";
123 report << " Average: " << std::fixed << std::setprecision(2)
124 << stats.avg_time_us << " μs\n";
125 report << " Median: " << std::fixed << std::setprecision(2)
126 << stats.median_time_us << " μs\n";
127 report << " Total: " << std::fixed << std::setprecision(2)
128 << stats.total_time_ms << " ms\n";
129
130 // Performance analysis
131 if (operation.find("palette_lookup") != std::string::npos) {
132 if (stats.avg_time_us < 1.0) {
133 report << " Status: ✓ OPTIMIZED (O(1) hash map lookup)\n";
134 } else {
135 report << " Status: ⚠ NEEDS OPTIMIZATION (O(n) linear search)\n";
136 }
137 } else if (operation.find("texture_update") != std::string::npos) {
138 if (stats.avg_time_us < 100.0) {
139 report << " Status: ✓ OPTIMIZED (dirty region tracking)\n";
140 } else {
141 report << " Status: ⚠ NEEDS OPTIMIZATION (full texture updates)\n";
142 }
143 } else if (operation.find("tile_cache") != std::string::npos) {
144 if (stats.avg_time_us < 10.0) {
145 report << " Status: ✓ OPTIMIZED (LRU cache hit)\n";
146 } else {
147 report << " Status: ⚠ CACHE MISS (tile recreation needed)\n";
148 }
149 } else if (operation.find("::Load") != std::string::npos) {
150 double avg_time_ms = stats.avg_time_us / 1000.0;
151 if (avg_time_ms < 100.0) {
152 report << " Status: ✓ FAST LOADING (< 100ms)\n";
153 } else if (avg_time_ms < 1000.0) {
154 report << " Status: ⚠ MODERATE LOADING (100-1000ms)\n";
155 } else {
156 report << " Status: ⚠ SLOW LOADING (> 1000ms)\n";
157 }
158 }
159
160 report << "\n";
161 }
162
163 // Overall performance summary
164 report << "=== Performance Summary ===\n";
165 size_t total_samples = 0;
166 double total_time = 0.0;
167
168 for (const auto& [operation, times] : operation_times_) {
169 total_samples += times.size();
170 total_time += std::accumulate(times.begin(), times.end(), 0.0);
171 }
172
173 if (total_samples > 0) {
174 report << "Total Samples: " << total_samples << "\n";
175 report << "Total Time: " << std::fixed << std::setprecision(2)
176 << total_time / 1000.0 << " ms\n";
177 report << "Average Time per Operation: " << std::fixed
178 << std::setprecision(2) << total_time / total_samples << " μs\n";
179 }
180
181 std::string report_str = report.str();
182
183 if (log_to_sdl) {
184 SDL_Log("%s", report_str.c_str());
185 }
186
187 return report_str;
188}
189
191 active_timers_.clear();
192 operation_times_.clear();
193 operation_totals_.clear();
194 operation_counts_.clear();
195}
196
197void PerformanceProfiler::ClearOperation(const std::string& operation_name) {
198 active_timers_.erase(operation_name);
199 operation_times_.erase(operation_name);
200 operation_totals_.erase(operation_name);
201 operation_counts_.erase(operation_name);
202}
203
204std::vector<std::string> PerformanceProfiler::GetOperationNames() const {
205 std::vector<std::string> names;
206 names.reserve(operation_times_.size());
207 for (const auto& [name, times] : operation_times_) {
208 names.push_back(name);
209 }
210 return names;
211}
212
213bool PerformanceProfiler::IsTiming(const std::string& operation_name) const {
214 return active_timers_.find(operation_name) != active_timers_.end();
215}
216
218 const std::string& operation_name) const {
219 auto total_it = operation_totals_.find(operation_name);
220 auto count_it = operation_counts_.find(operation_name);
221
222 if (total_it == operation_totals_.end() ||
223 count_it == operation_counts_.end() || count_it->second == 0) {
224 return 0.0;
225 }
226
227 return total_it->second / count_it->second;
228}
229
231 const std::string& operation_name) const {
232 auto total_it = operation_totals_.find(operation_name);
233 return (total_it != operation_totals_.end()) ? total_it->second : 0.0;
234}
235
237 const std::string& operation_name) const {
238 auto count_it = operation_counts_.find(operation_name);
239 return (count_it != operation_counts_.end()) ? count_it->second : 0;
240}
241
243 std::cout << "\n=== Performance Summary ===\n";
244 std::cout << std::left << std::setw(30) << "Operation" << std::setw(12)
245 << "Count" << std::setw(15) << "Total (ms)" << std::setw(15)
246 << "Average (ms)" << "\n";
247 std::cout << std::string(72, '-') << "\n";
248
249 for (const auto& [operation_name, times] : operation_times_) {
250 if (times.empty())
251 continue;
252
253 auto total_it = operation_totals_.find(operation_name);
254 auto count_it = operation_counts_.find(operation_name);
255
256 if (total_it != operation_totals_.end() &&
257 count_it != operation_counts_.end()) {
258 double total_time = total_it->second;
259 int count = count_it->second;
260 double avg_time = (count > 0) ? total_time / count : 0.0;
261
262 std::cout << std::left << std::setw(30) << operation_name << std::setw(12)
263 << count << std::setw(15) << std::fixed << std::setprecision(2)
264 << total_time << std::setw(15) << std::fixed
265 << std::setprecision(2) << avg_time << "\n";
266 }
267 }
268 std::cout << std::string(72, '-') << "\n";
269}
270
271double PerformanceProfiler::CalculateMedian(std::vector<double> values) {
272 if (values.empty()) {
273 return 0.0;
274 }
275
276 size_t size = values.size();
277 if (size % 2 == 0) {
278 return (values[size / 2 - 1] + values[size / 2]) / 2.0;
279 }
280 return values[size / 2];
281}
282
283// ScopedTimer implementation
284ScopedTimer::ScopedTimer(const std::string& operation_name)
285 : operation_name_(operation_name) {
288 }
289}
290
292 // Check if profiler is still valid (not shutting down) to prevent
293 // crashes during static destruction order issues
296 }
297}
298
299} // namespace gfx
300} // namespace yaze
std::pair< size_t, size_t > GetMemoryStats() const
Get memory usage statistics.
static MemoryPool & Get()
Unified performance profiler for all YAZE operations.
void Clear()
Clear all timing data.
void StartTimer(const std::string &operation_name)
Start timing an operation.
double GetAverageTime(const std::string &operation_name) const
Get the average time for an operation in milliseconds.
std::vector< std::string > GetOperationNames() const
Get list of all tracked operations.
TimingStats GetStats(const std::string &operation_name) const
void ClearOperation(const std::string &operation_name)
Clear timing data for a specific operation.
static PerformanceProfiler & Get()
int GetOperationCount(const std::string &operation_name) const
Get the number of times an operation was measured.
static double CalculateMedian(std::vector< double > values)
Calculate median value from a sorted vector.
std::string GenerateReport(bool log_to_sdl=true) const
Generate a comprehensive performance report.
void EndTimer(const std::string &operation_name)
End timing an operation.
std::unordered_map< std::string, int > operation_counts_
std::unordered_map< std::string, TimePoint > active_timers_
static bool IsValid()
Check if the profiler is in a valid state (not shutting down) This prevents crashes during static des...
static bool IsEnabled()
Check if performance monitoring is enabled.
std::unordered_map< std::string, double > operation_totals_
std::unordered_map< std::string, std::vector< double > > operation_times_
double GetTotalTime(const std::string &operation_name) const
Get the total time for an operation in milliseconds.
void PrintSummary() const
Print a summary of all operations to console.
bool IsTiming(const std::string &operation_name) const
Check if an operation is currently being timed.
ScopedTimer(const std::string &operation_name)
Get timing statistics for an operation.