1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
|
/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */
#include <algorithm>
#include <climits>
#include <cstring>
#include "System/TimeProfiler.h"
#include "System/GlobalRNG.h"
#include "System/StringHash.h"
#include "System/Log/ILog.h"
#include "System/Threading/SpringThreading.h"
#ifdef THREADPOOL
#include "System/Threading/ThreadPool.h"
#endif
static spring::spinlock profileMutex;
static spring::spinlock hashToNameMutex;
static spring::unordered_map<unsigned, std::string> hashToName;
static spring::unordered_map<unsigned, int> refCounters;
static CGlobalUnsyncedRNG profileColorRNG;
spring_time BasicTimer::GetDuration() const
{
return spring_difftime(spring_gettime(), startTime);
}
ScopedTimer::ScopedTimer(const unsigned _nameHash, bool _autoShowGraph, bool _specialTimer)
: BasicTimer(_nameHash)
// Game::SendClientProcUsage depends on "Sim" and "Draw" percentages, BenchMark on "Lua"
// note that address-comparison is intended here, timer names are (and must be) literals
, autoShowGraph(_autoShowGraph)
, specialTimer(_specialTimer)
{
auto iter = refCounters.find(nameHash);
if (iter == refCounters.end())
iter = refCounters.insert(std::pair<unsigned, int>(nameHash, 0)).first;
++(iter->second);
}
ScopedTimer::~ScopedTimer()
{
// no avoiding a second lookup since iterators can be invalidated with unordered_map
auto iter = refCounters.find(nameHash);
assert(iter != refCounters.end());
assert(iter->second > 0);
if (--(iter->second) == 0) {
profiler.AddTime(nameHash, startTime, GetDuration(), autoShowGraph, specialTimer, false);
}
}
ScopedOnceTimer::ScopedOnceTimer(const char* timerName, const char* timerFrmt): startTime(spring_gettime())
{
strncpy(name, timerName, sizeof(name));
strncpy(frmt, timerFrmt, sizeof(frmt));
name[sizeof(name) - 1] = 0;
frmt[sizeof(frmt) - 1] = 0;
}
ScopedOnceTimer::ScopedOnceTimer(const std::string& timerName, const char* timerFrmt): startTime(spring_gettime())
{
strncpy(name, timerName.c_str(), sizeof(name));
strncpy(frmt, timerFrmt , sizeof(frmt));
name[sizeof(name) - 1] = 0;
frmt[sizeof(frmt) - 1] = 0;
}
ScopedOnceTimer::~ScopedOnceTimer()
{
LOG(frmt, __func__, name, int(GetDuration().toMilliSecsi()));
}
spring_time ScopedOnceTimer::GetDuration() const
{
return spring_difftime(spring_gettime(), startTime);
}
ScopedMtTimer::ScopedMtTimer(unsigned _nameHash, bool _autoShowGraph)
: BasicTimer(_nameHash)
, autoShowGraph(_autoShowGraph)
{
}
ScopedMtTimer::~ScopedMtTimer()
{
profiler.AddTime(nameHash, startTime, GetDuration(), autoShowGraph, false, true);
}
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CTimeProfiler::CTimeProfiler()
{
// self
RegisterTimer("Misc::Profiler::AddTime");
// specials (conditional on LuaContextData)
RegisterTimer("Lua::Callins::Synced");
RegisterTimer("Lua::Callins::Unsynced");
RegisterTimer("Lua::CollectGarbage::Synced");
RegisterTimer("Lua::CollectGarbage::Unsynced");
ResetState();
}
#if 1
CTimeProfiler::~CTimeProfiler() = default;
#else
CTimeProfiler::~CTimeProfiler()
{
// should not be needed, destructor runs after main returns and all threads are gone
std::lock_guard<spring::spinlock> lock(profileMutex);
}
#endif
CTimeProfiler& CTimeProfiler::GetInstance()
{
static CTimeProfiler tp;
return tp;
}
bool CTimeProfiler::RegisterTimer(const char* timerName)
{
const unsigned nameHash = hashString(timerName);
std::lock_guard<spring::spinlock> lock(hashToNameMutex);
const auto iter = hashToName.find(nameHash);
if (iter == hashToName.end()) {
hashToName.insert(nameHash, timerName);
return true;
}
if (iter->second == timerName)
return true;
LOG_L(L_ERROR, "[%s] timer hash collision: %s <=> %s", __func__, timerName, iter->second.c_str());
assert(false);
return false;
}
bool CTimeProfiler::UnRegisterTimer(const char* timerName)
{
const unsigned nameHash = hashString(timerName);
std::lock_guard<spring::spinlock> lock(hashToNameMutex);
const auto iter = hashToName.find(nameHash);
if (iter == hashToName.end())
return false;
hashToName.erase(iter);
return true;
}
void CTimeProfiler::ResetState() {
// grab lock; ThreadPool workers might already be running SCOPED_MT_TIMER
std::lock_guard<spring::spinlock> lock(profileMutex);
profiles.clear();
profiles.reserve(128);
sortedProfiles.clear();
#ifdef THREADPOOL
threadProfiles.clear();
threadProfiles.resize(ThreadPool::GetMaxThreads());
#endif
profileColorRNG.Seed(spring_tomsecs(lastBigUpdate = spring_gettime()));
currentPosition = 0;
resortProfiles = 0;
enabled = false;
}
void CTimeProfiler::ToggleLock(bool lock)
{
if (lock) {
profileMutex.lock();
} else {
profileMutex.unlock();
}
}
void CTimeProfiler::Update()
{
if (!enabled) {
UpdateRaw();
ResortProfilesRaw();
RefreshProfilesRaw();
return;
}
// FIXME: non-locking threadsafe
std::lock_guard<spring::spinlock> lock(profileMutex);
UpdateRaw();
ResortProfilesRaw();
RefreshProfilesRaw();
}
void CTimeProfiler::UpdateRaw()
{
currentPosition += 1;
currentPosition &= (TimeRecord::numFrames - 1);
for (auto& pi: profiles) {
pi.second.frames[currentPosition] = spring_notime;
}
const spring_time curTime = spring_gettime();
const float timeDiff = spring_diffmsecs(curTime, lastBigUpdate);
if (timeDiff > 500.0f) {
// update percentages and peaks twice every second
for (auto& pi: profiles) {
auto& p = pi.second;
p.stats.y = spring_tomsecs(p.current) / timeDiff;
p.current = spring_notime;
p.newLagPeak = false;
p.newPeak = (p.stats.y > p.stats.z);
if (!p.newPeak)
continue;
p.stats.z = p.stats.y;
}
lastBigUpdate = curTime;
}
if (curTime.toSecsi() % 6 == 0) {
for (auto& pi: profiles) {
(pi.second).stats.x *= 0.5f;
}
}
}
void CTimeProfiler::ResortProfilesRaw()
{
if (resortProfiles > 0) {
resortProfiles = 0;
sortedProfiles.clear();
sortedProfiles.reserve(profiles.size());
typedef std::pair<std::string, TimeRecord> TimeRecordPair;
typedef std::function<bool(const TimeRecordPair&, const TimeRecordPair&)> ProfileSortFunc;
const ProfileSortFunc sortFunc = [](const TimeRecordPair& a, const TimeRecordPair& b) { return (a.first < b.first); };
// either caller already has lock, or we are disabled and thread-safe
{
std::lock_guard<spring::spinlock> lock(hashToNameMutex);
for (const auto& profile: profiles) {
const auto iter = hashToName.find(profile.first);
if (iter == hashToName.end()) {
LOG_L(L_ERROR, "[%s] timer with hash %u wasn't registered", __func__, profile.first);
assert(false);
hashToName.insert(profile.first, "???");
continue;
}
sortedProfiles.emplace_back(iter->second, profile.second);
}
}
std::sort(sortedProfiles.begin(), sortedProfiles.end(), sortFunc);
}
}
void CTimeProfiler::RefreshProfiles()
{
// ProfileDrawer calls this, and is only enabled when we are
assert(enabled);
// lock so nothing modifies *unsorted* profiles during the refresh
std::lock_guard<spring::spinlock> lock(profileMutex);
RefreshProfilesRaw();
}
void CTimeProfiler::RefreshProfilesRaw()
{
// either called from ProfileDrawer or from Update; the latter
// makes the "/debuginfo profiling" command work when disabled
for (auto& sortedProfile: sortedProfiles) {
TimeRecord& rec = sortedProfile.second;
const bool showGraph = rec.showGraph;
rec = profiles[hashString(sortedProfile.first.c_str())];
rec.showGraph = showGraph;
}
}
const CTimeProfiler::TimeRecord& CTimeProfiler::GetTimeRecord(const char* name) const
{
// if disabled, only special timers can pass AddTime
// all of those are non-threaded, so no need to lock
if (!enabled)
return (GetTimeRecordRaw(name));
std::lock_guard<spring::spinlock> lock(profileMutex);
return (GetTimeRecordRaw(name));
}
void CTimeProfiler::AddTime(
const unsigned nameHash,
const spring_time startTime,
const spring_time deltaTime,
const bool showGraph,
const bool specialTimer,
const bool threadTimer
) {
const spring_time t0 = spring_now();
if (!enabled) {
if (!specialTimer)
return;
assert(!threadTimer);
AddTimeRaw(nameHash, startTime, deltaTime, showGraph, threadTimer);
AddTimeRaw(hashString("Misc::Profiler::AddTime"), t0, spring_now() - t0, false, false);
return;
}
// acquire lock at the start; one inserting thread could
// cause a profile rehash and invalidate <pi> for another
std::lock_guard<spring::spinlock> lock(profileMutex);
AddTimeRaw(nameHash, startTime, deltaTime, showGraph, threadTimer);
AddTimeRaw(hashString("Misc::Profiler::AddTime"), t0, spring_now() - t0, false, false);
}
void CTimeProfiler::AddTimeRaw(
const unsigned nameHash,
const spring_time startTime,
const spring_time deltaTime,
const bool showGraph,
const bool threadTimer
) {
#ifdef THREADPOOL
if (threadTimer)
threadProfiles[ThreadPool::GetThreadNum()].emplace_back(startTime, spring_gettime());
#endif
auto pi = profiles.find(nameHash);
auto& p = (pi != profiles.end()) ? pi->second: profiles[nameHash];
// these are 0 if just created, works for both paths
p.total += deltaTime;
p.current += deltaTime;
p.newLagPeak = (p.stats.x > 0.0f && deltaTime.toMilliSecsf() > p.stats.x);
p.stats.x = std::max(p.stats.x, deltaTime.toMilliSecsf());
if (pi != profiles.end()) {
// profile already exists, add dt
p.frames[currentPosition] += deltaTime;
} else {
// new profile, new color
p.color.x = profileColorRNG.NextFloat();
p.color.y = profileColorRNG.NextFloat();
p.color.z = profileColorRNG.NextFloat();
p.showGraph = showGraph;
resortProfiles += 1;
}
}
void CTimeProfiler::PrintProfilingInfo() const
{
if (sortedProfiles.empty())
return;
LOG("%35s|%18s|%s", "Part", "Total Time", "Time of the last 0.5s");
for (const auto& sortedProfile: sortedProfiles) {
const std::string& name = sortedProfile.first;
const TimeRecord& tr = sortedProfile.second;
LOG("%35s %16.2fms %5.2f%%", name.c_str(), tr.total.toMilliSecsf(), tr.stats.y * 100);
}
}
|