Skip to content

Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.

feat(gameengine): measure the frame, and its tail

Olcay Seygan00be74a8e7d0
diff --git a/GeneralsMD/Code/CMakeLists.txt b/GeneralsMD/Code/CMakeLists.txt
index c8cc8aca4..bc428aad7 100644
--- a/GeneralsMD/Code/CMakeLists.txt
+++ b/GeneralsMD/Code/CMakeLists.txt
@@ -608,3 +608,26 @@ if(RELEASE_DEBUG_LOGGING)
target_compile_definitions(gameenginedevice PRIVATE RELEASE_DEBUG_LOGGING)
target_compile_definitions(generals PRIVATE RELEASE_DEBUG_LOGGING)
endif()
+
+# THREADING-ROADMAP.md section 0: the measurement build. EA's PerfGather call sites are all
+# over the frame already, but PerfTimer.h defines NO_PERF_TIMERS in *both* branches of its
+# #if, so PERF_TIMERS is off in every configuration and every USE_PERF_TIMER compiles to
+# nothing. This switch turns them on without touching the shipping default: the timers read
+# the TSC on every scope entry and exit, which is not free, so OFF is the right default and
+# any perf claim has to say which build it came from.
+#
+# Only the three targets that include PerfTimer.h get the define. It must not go on globally:
+# WWVegas' headers reach GameEngine's Debug.h, and a mismatched define across libraries is how
+# you get a link error at best and a silently different struct at worst.
+option(PERF_TIMERS "Compile EA's PerfGather scopes in (measurement build, not for shipping)" OFF)
+if(PERF_TIMERS)
+ target_compile_definitions(gameengine PRIVATE PERF_TIMERS)
+ target_compile_definitions(gameenginedevice PRIVATE PERF_TIMERS)
+ target_compile_definitions(generals PRIVATE PERF_TIMERS)
+ # A measurement build is not the build anyone plays, and its post-build step copies into the
+ # same Run/ directory the shipping one does. Renaming the output keeps the two side by side -
+ # which is also the only way to measure one against the other without rebuilding in between
+ # (ai-batch.ps1 -Exe takes the name).
+ set_target_properties(generals PROPERTIES OUTPUT_NAME generals_perf)
+ message(STATUS "PERF_TIMERS ON - measurement build, timers cost real time; exe is generals_perf.exe")
+endif()
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/PerfTimer.h b/GeneralsMD/Code/GameEngine/Include/Common/PerfTimer.h
index 1367fed61..16af20155 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/PerfTimer.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/PerfTimer.h
@@ -115,13 +115,44 @@ public:
static void dumpAll(UnsignedInt frame);
static void displayGraph(UnsignedInt frame);
+ /* THREADING-ROADMAP.md section 0 step 3: the per-frame CSV answers "what did frame 4312
+ cost", which is the wrong question when deciding what to thread. accumulateFrame() folds
+ the frame that just ended into a running total and dumpSummary() prints the average cost
+ per frame per scope at the end of the run, next to HEADLESS RESULT. Call accumulateFrame
+ exactly once per frame, before resetAll().
+
+ `frameMS` is the whole loop pass as the eye saw it. A pass longer than SPIKE_MS gets its
+ own line in the log with the scopes that owned it, because an average cannot tell you what
+ a stutter was - only the frame it happened on can, and by the end of the run that frame is
+ long gone. */
+ enum { SPIKE_MS = 17 }; // one frame at 60Hz; anything longer is visible
+
+ static void accumulateFrame(Real frameMS);
+ static void dumpSummary();
+
void reset();
private:
+ /* The stack of gathers currently open, so a scope can subtract its children's time from its
+ own. Per *thread*, not per process: CriticalSection::enter and FileSystem::openFile both
+ carry a gather and both are called from threads that are not the main one (the texture
+ loader, the log writer, the job pool). Sharing one stack between them walks the head off
+ the end of the array and corrupts whatever static happens to sit after it - which is what
+ a PERF_TIMERS build used to die of on its first rendered frame.
+
+ An index rather than a pointer because a thread-local pointer cannot be initialised with
+ the address of a thread-local array; the index is zero-initialised per thread for free,
+ and slot 0 stays the NULL "no parent" sentinel. */
enum { MAX_ACTIVE_STACK = 256 };
- static PerfGather* m_active[MAX_ACTIVE_STACK];
- static PerfGather** m_activeHead;
+ static __declspec(thread) PerfGather* m_active[MAX_ACTIVE_STACK];
+ static __declspec(thread) Int m_activeDepth;
+ /* TRUE only on the thread initPerfDump() was called from. The counters below are shared and
+ an Int64 += is two writes on x86, so a gather on a scope several threads enter (CritSec,
+ FileSystem) used to report torn nonsense - the FileSystem row came out at 27 *seconds* per
+ frame. Only the profiled thread accumulates now, which is also the right answer to the
+ question the table exists for: where the frame goes is where the main thread goes. */
+ static __declspec(thread) Bool m_gatherOnThisThread;
static Int64 s_stopStartOverhead; // overhead for stop+start a timer
static PerfGather*& getHeadPtr();
@@ -129,11 +160,20 @@ private:
void addToList();
void removeFromList();
+ /* The counters below are shared, and a gather on a scope that several threads enter (CritSec,
+ FileSystem) has them incremented from several threads without a lock. On x86 an Int64 +=
+ is two writes, so such a row can be off by a torn update. Left alone deliberately: this is
+ a measurement build, the affected rows are the ones whose absolute value nobody acts on,
+ and making them atomic would cost more than the thing being measured. */
const char* m_identifier;
Int64 m_startTime;
Int64 m_runningTimeGross;
Int64 m_runningTimeNet;
Int m_callCount;
+ Int64 m_totalTimeNet; // summed over every frame accumulateFrame() saw
+ Int64 m_totalTimeGross;
+ Int64 m_totalCallCount;
+ Int64 m_worstFrameNet; // the single worst frame this scope ever had
PerfGather* m_next;
PerfGather* m_prev;
Bool m_ignore;
@@ -143,7 +183,13 @@ private:
//-------------------------------------------------------------------------------------------------
void PerfGather::startTimer()
{
- *++m_activeHead = this;
+ if (!m_gatherOnThisThread)
+ return;
+
+ // The depth moves whether or not the slot exists, so start and stop stay balanced even if
+ // something nests deeper than the array; only the parent attribution is lost.
+ if (++m_activeDepth < MAX_ACTIVE_STACK)
+ m_active[m_activeDepth] = this;
GetPrecisionTimer(&m_startTime);
}
@@ -152,6 +198,9 @@ void PerfGather::stopTimer()
{
DEBUG_ASSERTCRASH(this != NULL, ("I am null, uh oh"));
+ if (!m_gatherOnThisThread)
+ return;
+
Int64 runTime;
GetPrecisionTimer(&runTime);
@@ -163,18 +212,18 @@ void PerfGather::stopTimer()
++m_callCount;
#ifdef _DEBUG
- DEBUG_ASSERTCRASH(*m_activeHead != NULL, ("m_activeHead is null, uh oh"));
- DEBUG_ASSERTCRASH(*m_activeHead == this, ("I am not the active timer, uh oh"));
- DEBUG_ASSERTCRASH(m_activeHead >= &m_active[0] && m_activeHead <= &m_active[MAX_ACTIVE_STACK-1], ("active under/over flow"));
+ DEBUG_ASSERTCRASH(m_activeDepth > 0 && m_activeDepth < MAX_ACTIVE_STACK, ("active under/over flow"));
+ DEBUG_ASSERTCRASH(m_active[m_activeDepth] == this, ("I am not the active timer, uh oh"));
#endif
- --m_activeHead;
+ --m_activeDepth;
- if (*m_activeHead)
+ PerfGather *parent = (m_activeDepth > 0 && m_activeDepth < MAX_ACTIVE_STACK) ? m_active[m_activeDepth] : NULL;
+ if (parent)
{
// don't add the time it took for us to actually get the ticks (in startTimer) to our parent...
- (*m_activeHead)->m_runningTimeGross -= (s_stopStartOverhead);
- if ((*m_activeHead)->m_netTimeOnly) {
- (*m_activeHead)->m_runningTimeNet -= (runTime + s_stopStartOverhead);
+ parent->m_runningTimeGross -= (s_stopStartOverhead);
+ if (parent->m_netTimeOnly) {
+ parent->m_runningTimeNet -= (runTime + s_stopStartOverhead);
}
}
}
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
index 48f8b65bb..ea962b0be 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
@@ -50,6 +50,7 @@
#include "Common/CDManager.h"
#include "Common/GlobalData.h"
#include "Common/PerfTimer.h"
+#include "Common/JobSystem.h"
#include "Common/RandomValue.h"
#include "Common/NameKeyGenerator.h"
#include "Common/ModuleFactory.h"
@@ -245,6 +246,11 @@ GameEngine::~GameEngine()
_Module.Term();
+ /* After everything that could still fork. parallel_for never returns with work in flight, so
+ there is nothing to drain here - but a worker parked on the semaphore still has to be told
+ to leave, or the process waits on it at exit. */
+ JobSystem::shutdown();
+
#ifdef PERF_TIMERS
PerfGather::termPerfDump();
#endif
@@ -485,6 +491,10 @@ void GameEngine::init( int argc, char *argv[] )
m_maxFPS = DEFAULT_MAX_FPS;
+ /* THREADING-ROADMAP.md 3.1. Started before anything can fork and joined in ~GameEngine.
+ Costs one thread per spare core sitting on a semaphore until something uses it. */
+ JobSystem::init();
+
TheSubsystemList = MSGNEW("GameEngineSubsystem") SubsystemInterfaceList;
TheSubsystemList->addSubsystem(this);
@@ -1043,6 +1053,10 @@ extern Real TheWindowRepaintMS; ///< ...and the window system's repaint
extern Real TheStripGatherMS; ///< ...of the overlays, the production strip's sweep
extern Real TheStripDrawMS; ///< ...and the production strip's own drawing
+#endif
+
+// Outside the DEBUG_LOGGING block above on purpose: the frame-time histogram below is not debug
+// instrumentation, it ships, and it needs this.
static Real engineElapsedMS( const Int64 &from, const Int64 &to )
{
Int64 freq;
@@ -1051,7 +1065,154 @@ static Real engineElapsedMS( const Int64 &from, const Int64 &to )
return 0.0f;
return (Real)((double)(to - from) * 1000.0 / (double)freq);
}
-#endif
+
+/** -----------------------------------------------------------------------------------------------
+ * Frame time as a distribution, not as an average.
+ *
+ * A mean is exactly the statistic that hides a stutter: a match that runs at 3ms and hitches to
+ * 120ms four times a minute has a beautiful average and is horrible to play. What a player feels
+ * is the tail - so this keeps the tail and throws the mean in as an afterthought.
+ *
+ * A fixed histogram, because the alternative is keeping every sample: 0.25ms buckets out to 64ms
+ * plus one overflow bucket, which is 257 Ints of static storage, no allocation, and one add per
+ * frame. Percentiles come out of the buckets (so they are accurate to a quarter of a millisecond,
+ * which is far finer than anything that matters here); the worst frame is kept exactly, because the
+ * worst frame is the one that gets complained about.
+ */
+class FrameTimeHistogram
+{
+public:
+ enum { BUCKET_COUNT = 257, LAST_BUCKET = BUCKET_COUNT - 1 };
+ static const Real BUCKET_MS; // width of one bucket
+
+ void reset( void )
+ {
+ m_count = 0;
+ m_sumMS = 0.0;
+ m_worstMS = 0.0f;
+ m_worstAtFrame = 0;
+ for( Int i = 0; i < BUCKET_COUNT; ++i )
+ m_buckets[ i ] = 0;
+ }
+
+ void note( Real ms, UnsignedInt logicFrame )
+ {
+ if( ms < 0.0f )
+ return; // a clock that went backwards is not a frame time
+
+ ++m_count;
+ m_sumMS += ms;
+ if( ms > m_worstMS )
+ {
+ m_worstMS = ms;
+ m_worstAtFrame = logicFrame;
+ }
+
+ Int bucket = (Int)(ms / BUCKET_MS);
+ if( bucket > LAST_BUCKET )
+ bucket = LAST_BUCKET; // everything past 64ms lands together; it is all "terrible"
+ ++m_buckets[ bucket ];
+ }
+
+ Int count( void ) const { return m_count; }
+ Real worstMS( void ) const { return m_worstMS; }
+ UnsignedInt worstAtFrame( void ) const { return m_worstAtFrame; }
+ Real meanMS( void ) const { return m_count ? (Real)(m_sumMS / m_count) : 0.0f; }
+
+ /** The bucket boundary at or below which `fraction` of the frames fall. Reported as the top of
+ the bucket, so it never claims a frame was faster than it was. */
+ Real percentileMS( Real fraction ) const
+ {
+ if( m_count <= 0 )
+ return 0.0f;
+ const Int target = (Int)(fraction * m_count);
+ Int running = 0;
+ for( Int i = 0; i < BUCKET_COUNT; ++i )
+ {
+ running += m_buckets[ i ];
+ if( running > target )
+ return (i == LAST_BUCKET) ? m_worstMS : (Real)(i + 1) * BUCKET_MS;
+ }
+ return m_worstMS;
+ }
+
+ /** How many frames took longer than `ms`. This is the stutter count: pick the budget the
+ frame is supposed to fit in and this says how often it did not. */
+ Int countOver( Real ms ) const
+ {
+ Int over = 0;
+ const Int firstBad = (Int)(ms / BUCKET_MS) + 1;
+ for( Int i = firstBad; i < BUCKET_COUNT; ++i )
+ over += m_buckets[ i ];
+ return over;
+ }
+
+private:
+ Int m_buckets[ BUCKET_COUNT ];
+ Int m_count;
+ double m_sumMS;
+ Real m_worstMS;
+ UnsignedInt m_worstAtFrame;
+};
+
+const Real FrameTimeHistogram::BUCKET_MS = 0.25f;
+
+/* One for the whole loop pass - what the player's eye is on - and one for the logic tick alone,
+ because those are two different stutters with two different fixes: a long render frame drops a
+ picture, a logic tick over its 33ms budget drops the whole simulation behind the wall clock. */
+static FrameTimeHistogram theFrameTimes;
+static FrameTimeHistogram theLogicTimes;
+static Bool theFrameTimesStarted = FALSE;
+
+void GameEngine_noteFrameTime( Real ms, UnsignedInt logicFrame )
+{
+ if( !theFrameTimesStarted )
+ return;
+ theFrameTimes.note( ms, logicFrame );
+}
+
+void GameEngine_noteLogicTime( Real ms, UnsignedInt logicFrame )
+{
+ if( !theFrameTimesStarted )
+ return;
+ theLogicTimes.note( ms, logicFrame );
+}
+
+/** Start counting. Called when an unattended run actually begins, so the map load, the first
+ asset pass and the settling second are not counted as stutters - they are, but they are not the
+ kind anybody can do anything about, and leaving them in buries the ones that matter. */
+static void startFrameTimeStats( void )
+{
+ theFrameTimes.reset();
+ theLogicTimes.reset();
+ theFrameTimesStarted = TRUE;
+}
+
+static void reportFrameTimeStats( void )
+{
+ if( theFrameTimes.count() <= 0 )
+ return;
+
+ const Real over16 = 100.0f * theFrameTimes.countOver( 16.7f ) / theFrameTimes.count();
+ const Real over33 = 100.0f * theFrameTimes.countOver( 33.3f ) / theFrameTimes.count();
+ DEBUG_LOG(("HEADLESS FRAMETIME: %d frames | mean %.2f p50 %.2f p95 %.2f p99 %.2f p99.9 %.2f worst %.2f ms (frame %d) | over 16.7ms %d (%.2f%%) | over 33.3ms %d (%.2f%%)\n",
+ theFrameTimes.count(), theFrameTimes.meanMS(),
+ theFrameTimes.percentileMS( 0.50f ), theFrameTimes.percentileMS( 0.95f ),
+ theFrameTimes.percentileMS( 0.99f ), theFrameTimes.percentileMS( 0.999f ),
+ theFrameTimes.worstMS(), theFrameTimes.worstAtFrame(),
+ theFrameTimes.countOver( 16.7f ), over16,
+ theFrameTimes.countOver( 33.3f ), over33));
+
+ if( theLogicTimes.count() > 0 )
+ {
+ DEBUG_LOG(("HEADLESS LOGICTIME: %d ticks | mean %.2f p50 %.2f p95 %.2f p99 %.2f p99.9 %.2f worst %.2f ms (frame %d) | over 33.3ms %d\n",
+ theLogicTimes.count(), theLogicTimes.meanMS(),
+ theLogicTimes.percentileMS( 0.50f ), theLogicTimes.percentileMS( 0.95f ),
+ theLogicTimes.percentileMS( 0.99f ), theLogicTimes.percentileMS( 0.999f ),
+ theLogicTimes.worstMS(), theLogicTimes.worstAtFrame(),
+ theLogicTimes.countOver( 33.3f )));
+ }
+}
/** -----------------------------------------------------------------------------------------------
* Why an unattended run is over, or NULL while it is still going. The string is what the log line
@@ -1079,7 +1240,12 @@ const char *GameEngine_headlessRunResult( UnsignedInt frame, UnsignedInt victory
*/
static void updateHeadlessRun( void )
{
- if (!TheGlobalData->m_headless || !TheGameLogic->isInGame() || TheGameLogic->isInShellGame())
+ /* -autoskirmish counts as unattended even when it draws. THREADING-ROADMAP.md section 0 step 4
+ asks for a heavy scenario under a real renderer, and a run that never ends and never writes
+ its numbers down is not a measurement. This still cannot fire on a game a person started:
+ reaching here needs -headless or -autoskirmish, and neither is on a menu. */
+ const Bool unattended = TheGlobalData->m_headless || TheGlobalData->m_autoSkirmishPlayers > 0;
+ if (!unattended || !TheGameLogic->isInGame() || TheGameLogic->isInShellGame())
return;
static DWORD runStartTime = 0;
@@ -1097,6 +1263,12 @@ static void updateHeadlessRun( void )
const UnsignedInt frame = TheGameLogic->getFrame();
+ /* The frame times start a second in, not at frame 0. The first counted pass carries the tail
+ of the map load and came out at two full seconds, which then *is* the worst frame of the
+ match and buries the 60ms hitch that somebody could actually do something about. */
+ if( !theFrameTimesStarted && frame > runStartFrame + LOGICFRAMES_PER_SECOND )
+ startFrameTimeStats();
+
/* The biggest army each side ever fielded, sampled once a second. The end-of-match counts are
cumulative and cannot tell an AI that massed and traded evenly from one that trickled units
out and lost them one at a time. Once a second is one walk of each player's object list per
@@ -1137,6 +1309,21 @@ static void updateHeadlessRun( void )
// reduced the traffic jams it was supposed to reduce.
DEBUG_LOG(("HEADLESS PATHFIND: %s\n", Pathfinder::getMatchProfileReport()));
+ /* Stability, which is a different question from speed and is answered by the tail rather than
+ by the average. These two lines are the ones a stutter complaint is argued with. */
+ reportFrameTimeStats();
+
+ /* THREADING-ROADMAP.md 3.1's safety net: "no allocation inside a job" is a rule, and a rule
+ nothing checks is a comment. allocs must read 0 - anything else means a job took the one
+ global pool lock and serialized the fork it was supposed to spread. */
+ DEBUG_LOG(("HEADLESS JOBS: %d worker threads, %d allocations from a job\n",
+ JobSystem::workerCount(), JobSystem::workerAllocationCount()));
+
+ // THREADING-ROADMAP.md section 0 step 3. Only a PERF_TIMERS build has anything to say here.
+#ifdef PERF_TIMERS
+ PerfGather::dumpSummary();
+#endif
+
for( Int i = 0; i < ThePlayerList->getPlayerCount(); ++i )
{
Player *p = ThePlayerList->getNthPlayer( i );
@@ -1299,6 +1486,9 @@ void GameEngine::update( void )
QueryPerformanceCounter( (LARGE_INTEGER *)&tLogicEnd );
logicMS = engineElapsedMS( tLogicStart, tLogicEnd );
logicTicks = logicTicksThisPass;
+ // One pass can pay off several ticks of debt; charge the histogram per tick, or a
+ // catch-up burst reads as one enormous logic frame that never actually happened.
+ GameEngine_noteLogicTime( logicMS / (Real)logicTicksThisPass, TheGameLogic->getFrame() );
#endif
}
@@ -1382,6 +1572,7 @@ void GameEngine::execute( void )
// pretty basic for now
while( !m_quitting )
{
+ Real thisFrameMS = 0.0f; // how long this pass took, for the stutter report at the bottom
//if (TheGlobalData->m_vTune)
{
@@ -1415,7 +1606,12 @@ void GameEngine::execute( void )
#endif
{
- try
+ /* The whole pass, which is what the eye is on: everything between one picture and
+ the next, not just the parts somebody remembered to instrument. Two
+ QueryPerformanceCounter reads a frame, which is why this is not behind a switch. */
+ Int64 tFrameStart, tFrameEnd;
+ QueryPerformanceCounter( (LARGE_INTEGER *)&tFrameStart );
+ try
{
// compute a frame
update();
@@ -1441,6 +1637,10 @@ void GameEngine::execute( void )
}
RELEASE_CRASH(("Uncaught Exception in GameEngine::update"));
} // catch
+ QueryPerformanceCounter( (LARGE_INTEGER *)&tFrameEnd );
+ thisFrameMS = engineElapsedMS( tFrameStart, tFrameEnd );
+ GameEngine_noteFrameTime( thisFrameMS,
+ TheGameLogic ? TheGameLogic->getFrame() : 0 );
} // perf
{
@@ -1464,6 +1664,7 @@ void GameEngine::execute( void )
#ifdef PERF_TIMERS
if (!m_quitting && TheGameLogic->isInGame() && !TheGameLogic->isInShellGame() && !TheGameLogic->isGamePaused())
{
+ PerfGather::accumulateFrame(thisFrameMS);
PerfGather::dumpAll(TheGameLogic->getFrame());
PerfGather::displayGraph(TheGameLogic->getFrame());
PerfGather::resetAll();
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/PerfTimer.cpp b/GeneralsMD/Code/GameEngine/Source/Common/PerfTimer.cpp
index 0dd5628ab..ba2ab397c 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/PerfTimer.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/PerfTimer.cpp
@@ -256,7 +256,7 @@ public:
{
if (m_outputStats[i].first == id)
{
- m_outputStats.erase(&m_outputStats[i]);
+ m_outputStats.erase(m_outputStats.begin() + i);
return;
}
}
@@ -272,9 +272,10 @@ static Int s_perfDumpOptions = 0;
static UnsignedInt s_lastDumpedFrame = 0;
static char s_buf[256] = "";
-PerfGather* PerfGather::m_active[MAX_ACTIVE_STACK] = { 0 };
-PerfGather** PerfGather::m_activeHead = &PerfGather::m_active[0];
-Int64 PerfGather::s_stopStartOverhead = -1;
+__declspec(thread) PerfGather* PerfGather::m_active[MAX_ACTIVE_STACK] = { 0 };
+__declspec(thread) Int PerfGather::m_activeDepth = 0;
+__declspec(thread) Bool PerfGather::m_gatherOnThisThread = FALSE;
+Int64 PerfGather::s_stopStartOverhead = -1;
//-------------------------------------------------------------------------------------------------
@@ -318,17 +319,25 @@ void PerfGather::removeFromList()
}
//-------------------------------------------------------------------------------------------------
-PerfGather::PerfGather(const char *identifier) :
- m_identifier(identifier),
- m_startTime(0),
- m_runningTimeGross(0),
- m_runningTimeNet(0),
+// The header has declared this with a netOnly flag since EA added DECLARE_TOTAL_PERF_TIMER;
+// the definition never grew it, because nothing has compiled this file since. Without the
+// parameter every gather is a net-time gather and DECLARE_TOTAL_PERF_TIMER does not link.
+PerfGather::PerfGather(const char *identifier, Bool netOnly) :
+ m_identifier(identifier),
+ m_startTime(0),
+ m_runningTimeGross(0),
+ m_runningTimeNet(0),
m_callCount(0),
+ m_totalTimeNet(0),
+ m_totalTimeGross(0),
+ m_totalCallCount(0),
+ m_worstFrameNet(0),
m_next(0),
- m_prev(0)
+ m_prev(0),
+ m_netTimeOnly(netOnly)
{
//Added By Sadullah Nader
- //Initializations inserted
+ //Initializations inserted
m_ignore = FALSE;
//
DEBUG_ASSERTCRASH(strchr(m_identifier, ',') == NULL, ("PerfGather names must not contain commas"));
@@ -359,9 +368,118 @@ void PerfGather::reset()
}
}
+//-------------------------------------------------------------------------------------------------
+static UnsignedInt s_framesAccumulated = 0;
+
+/*static*/ void PerfGather::accumulateFrame(Real frameMS)
+{
+ // The first second of a match loads assets and would drown every average that follows,
+ // which is the same reason dumpAll() skips it.
+ if (TheGameLogic && TheGameLogic->getFrame() <= 30)
+ return;
+
+ ++s_framesAccumulated;
+ for (PerfGather* head = getHeadPtr(); head != NULL; head = head->m_next)
+ {
+ head->m_totalTimeNet += head->m_runningTimeNet;
+ head->m_totalTimeGross += head->m_runningTimeGross;
+ head->m_totalCallCount += head->m_callCount;
+ if (head->m_runningTimeNet > head->m_worstFrameNet)
+ head->m_worstFrameNet = head->m_runningTimeNet;
+ }
+
+ /* A frame nobody would have noticed needs no report; a frame that dropped a picture needs one
+ while the evidence is still in the gathers, because resetAll() is about to throw it away.
+ Written as one line so a run's stutters can be read off the log with a grep. */
+ if (frameMS < (Real)SPIKE_MS || s_ticksPerUSec <= 0.0)
+ return;
+
+ char line[1024];
+ Int used = sprintf(line, "HEADLESS SPIKE: frame %d took %.1f ms |",
+ TheGameLogic ? TheGameLogic->getFrame() : 0, frameMS);
+
+ // The four worst scopes of this frame, by net time. Four because a fifth has never yet been
+ // the answer and the line has to stay one line.
+ enum { TOP = 4 };
+ const PerfGather* picked[ TOP ] = { 0 };
+ for (Int slot = 0; slot < TOP; ++slot)
+ {
+ const PerfGather* best = NULL;
+ Int64 bestTime = 0;
+ for (const PerfGather* head = getHeadPtr(); head != NULL; head = head->m_next)
+ {
+ if (head->m_runningTimeNet <= bestTime)
+ continue;
+ Bool taken = FALSE;
+ for (Int i = 0; i < slot; ++i)
+ if (picked[i] == head) { taken = TRUE; break; }
+ if (!taken)
+ {
+ best = head;
+ bestTime = head->m_runningTimeNet;
+ }
+ }
+ if (best == NULL)
+ break;
+ picked[ slot ] = best;
+ const double ms = (double)bestTime / s_ticksPerUSec / 1000.0;
+ if (ms < 0.05)
+ break; // nothing left worth naming
+ if (used > (Int)sizeof(line) - 64)
+ break;
+ used += sprintf(line + used, " %s %.1f", best->m_identifier, ms);
+ }
+ DEBUG_LOG(("%s\n", line));
+}
+
+//-------------------------------------------------------------------------------------------------
+/*static*/ void PerfGather::dumpSummary()
+{
+ if (s_framesAccumulated == 0 || s_ticksPerUSec <= 0.0)
+ {
+ DEBUG_LOG(("HEADLESS PERF: nothing gathered\n"));
+ return;
+ }
+
+ // Sorted by net time, because the only question this table exists to answer is "what is the
+ // frame actually spent on". Insertion sort over a list that is a few dozen long at most.
+ enum { MAX_ROWS = 256 };
+ const PerfGather* rows[MAX_ROWS];
+ Int numRows = 0;
+ for (const PerfGather* head = getHeadPtr(); head != NULL && numRows < MAX_ROWS; head = head->m_next)
+ {
+ if (head->m_totalCallCount == 0)
+ continue;
+ Int at = numRows++;
+ while (at > 0 && rows[at-1]->m_totalTimeNet < head->m_totalTimeNet)
+ {
+ rows[at] = rows[at-1];
+ --at;
+ }
+ rows[at] = head;
+ }
+
+ DEBUG_LOG(("HEADLESS PERF: %d frames gathered, us/frame net (gross) x calls/frame, worst single frame\n", s_framesAccumulated));
+ for (Int i = 0; i < numRows; ++i)
+ {
+ const PerfGather* g = rows[i];
+ // The worst column is the stability column: a scope whose average is nothing and whose
+ // worst frame is twenty milliseconds is a stutter, and the average alone hides it.
+ DEBUG_LOG(("HEADLESS PERF %s: %.1f (%.1f) x%.2f worst %.1f\n",
+ g->m_identifier,
+ (double)g->m_totalTimeNet / s_ticksPerUSec / s_framesAccumulated,
+ (double)g->m_totalTimeGross / s_ticksPerUSec / s_framesAccumulated,
+ (double)g->m_totalCallCount / s_framesAccumulated,
+ (double)g->m_worstFrameNet / s_ticksPerUSec));
+ }
+}
+
//-------------------------------------------------------------------------------------------------
/*static*/ void PerfGather::initPerfDump(const char* fname, Int options)
{
+ // Whichever thread sets the profile up is the one whose frame is being measured.
+ m_gatherOnThisThread = TRUE;
+
PerfGather::termPerfDump();
strcpy(s_buf, fname);
@@ -607,11 +725,11 @@ void PerfTimer::outputInfo( void )
return;
}
-#if defined(_DEBUG) || defined(_INTERNAL)
+ // Not under _DEBUG/_INTERNAL: the DEBUG_LOG below uses these in every configuration a
+ // PERF_TIMERS build can be, and a Release measurement build is exactly such a configuration.
double totalTimeInMS = 1000.0 * m_runningTime / s_ticksPerSec;
double avgTimePerFrame = totalTimeInMS / (m_lastFrame - m_startFrame + 1);
double avgTimePerCall = totalTimeInMS / m_callCount;
-#endif
if (m_crashWithInfo) {
DEBUG_CRASH(("%s\n"
@@ -645,11 +763,9 @@ void PerfTimer::outputInfo( void )
//-------------------------------------------------------------------------------------------------
void PerfTimer::showMetrics( void )
{
-#if defined(_DEBUG) || defined(_INTERNAL)
double totalTimeInMS = 1000.0 * m_runningTime / s_ticksPerSec;
double avgTimePerFrame = totalTimeInMS / (m_lastFrame - m_startFrame + 1);
double avgTimePerCall = totalTimeInMS / m_callCount;
-#endif
// we want to work on the thing in the array, so just store a reference.
AsciiString &outputStats = s_output.getStatsString(m_identifier);
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp
index d2b5b59ea..8425cd0c1 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp
@@ -1240,10 +1240,10 @@ void Drawable::imitateStealthLook( Drawable& otherDraw )
//-------------------------------------------------------------------------------------------------
/** update is called once per frame */
//-------------------------------------------------------------------------------------------------
-//DECLARE_PERF_TIMER(updateDrawable)
+DECLARE_PERF_TIMER(updateDrawable)
void Drawable::updateDrawable( void )
{
- //USE_PERF_TIMER(updateDrawable)
+ USE_PERF_TIMER(updateDrawable)
UnsignedInt now = TheGameLogic->getFrame();
Object *obj = getObject();
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GraphDraw.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GraphDraw.cpp
index 3db0c78a2..18a53a47a 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GraphDraw.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GraphDraw.cpp
@@ -88,10 +88,12 @@ void GraphDraw::render()
Int start = width * 0.33f;
width -= start;
+ // Both of these are read only by the two asserts below, which compile out in a Release
+ // PERF_TIMERS build - and BaseType.h:80 makes "initialized but not referenced" an error.
Int height = TheDisplay->getHeight();
-
Int totalCount = m_graphEntries.size();
- DEBUG_ASSERTCRASH(totalCount < MAX_GRAPH_VALUES, ("MAX_GRAPH_VALUES must be increased, not all labels will appear (max %d, cur %d).\n",MAX_GRAPH_VALUES,totalCount));
+ (void)height; (void)totalCount;
+ DEBUG_ASSERTCRASH(totalCount < MAX_GRAPH_VALUES,("MAX_GRAPH_VALUES must be increased, not all labels will appear (max %d, cur %d).\n",MAX_GRAPH_VALUES,totalCount));
DEBUG_ASSERTCRASH(BAR_HEIGHT * totalCount < height, ("BAR_HEIGHT must be reduced, as bars are being drawn off-screen.\n"));
VecGraphEntriesIt it;
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp
index 8e3ddf182..861cca572 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp
@@ -1925,10 +1925,10 @@ void InGameUI::preDraw( void )
//-------------------------------------------------------------------------------------------------
/** Update the in game user interface */
//-------------------------------------------------------------------------------------------------
-//DECLARE_PERF_TIMER(InGameUI_update)
+DECLARE_PERF_TIMER(InGameUI_update)
void InGameUI::update( void )
-{
- //USE_PERF_TIMER(InGameUI_update)
+{
+ USE_PERF_TIMER(InGameUI_update)
Int i;
/// @todo make sure this code gets called even when the UI is not being drawn
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp
index a52e890fe..2daedc9aa 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp
@@ -3190,7 +3190,7 @@ void ParticleSystemManager::reset( void )
// ------------------------------------------------------------------------------------------------
/** Update all particle systems */
// ------------------------------------------------------------------------------------------------
-//DECLARE_PERF_TIMER(ParticleSystemManager)
+DECLARE_PERF_TIMER(ParticleSystemManager)
void ParticleSystemManager::update( void )
{
if (m_lastLogicFrameUpdate == TheGameLogic->getFrame()) {
@@ -3200,7 +3200,7 @@ void ParticleSystemManager::update( void )
// update the last logic frame.
m_lastLogicFrameUpdate = TheGameLogic->getFrame();
- //USE_PERF_TIMER(ParticleSystemManager)
+ USE_PERF_TIMER(ParticleSystemManager)
ParticleSystem *sys;
for(ParticleSystemListIt it = m_allParticleSystemList.begin(); it != m_allParticleSystemList.end();)
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/FlatHeightMap.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/FlatHeightMap.cpp
index 4d9fb4584..900d660a4 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/FlatHeightMap.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/FlatHeightMap.cpp
@@ -457,11 +457,11 @@ void FlatHeightMapRenderObjClass::updateCenter(CameraClass *camera , RefRenderOb
//=============================================================================
/** Renders (draws) the terrain. */
//=============================================================================
-//DECLARE_PERF_TIMER(Terrain_Render)
+DECLARE_PERF_TIMER(Terrain_Render_Flat)
void FlatHeightMapRenderObjClass::Render(RenderInfoClass & rinfo)
{
- //USE_PERF_TIMER(Terrain_Render)
+ USE_PERF_TIMER(Terrain_Render_Flat)
Int devicePasses;
W3DShaderManager::ShaderTypes st;
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DShadow.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DShadow.cpp
index 0567f2edf..6d6fbf1df 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DShadow.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DShadow.cpp
@@ -64,10 +64,10 @@ Vector3 LightPosWorld[ MAX_SHADOW_LIGHTS ] =
Vector3( 94.0161f, 50.499f, 200.0f)
};
-//DECLARE_PERF_TIMER(shadowsRender)
+DECLARE_PERF_TIMER(shadowsRender)
void DoShadows(RenderInfoClass & rinfo, Bool stencilPass)
{
- //USE_PERF_TIMER(shadowsRender)
+ USE_PERF_TIMER(shadowsRender)
shadowCameraFrustum=&rinfo.Camera.Get_Frustum();
Int projectionCount=0;
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
index ceba17894..1e614b6c3 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
@@ -1680,12 +1680,12 @@ Int W3DDisplay::getLastFrameDrawCalls()
return Debug_Statistics::Get_Draw_Calls();
}
-//DECLARE_PERF_TIMER(BigAssRenderLoop)
+DECLARE_PERF_TIMER(BigAssRenderLoop)
// W3DDisplay::draw ===========================================================
/** Draw the entire W3D Display */
//=============================================================================
-//DECLARE_PERF_TIMER(W3DDisplay_draw)
+DECLARE_PERF_TIMER(W3DDisplay_draw)
static Bool s_screenShotPending = FALSE; // F12 pressed: save the frame at the end of the next draw()
static void saveScreenShot(void);
@@ -1710,7 +1710,7 @@ static Real w3dElapsedMS( const Int64 &from, const Int64 &to )
void W3DDisplay::draw( void )
{
- //USE_PERF_TIMER(W3DDisplay_draw)
+ USE_PERF_TIMER(W3DDisplay_draw)
static UnsignedInt syncTime = 0;
extern HWND ApplicationHWnd;
@@ -1957,7 +1957,7 @@ AGAIN:
if ( (TheGameLogic->getFrame() % 30 == 1) || ( ! (!TheGameLogic->isGamePaused() && TheGlobalData->m_TiVOFastMode && TheGameLogic->isInReplayGame())) )
#endif
{
- //USE_PERF_TIMER(BigAssRenderLoop)
+ USE_PERF_TIMER(BigAssRenderLoop)
static Bool couldRender = true;
if ((TheGlobalData->m_breakTheMovie == FALSE) && (TheGlobalData->m_disableRender == false) && WW3D::Begin_Render( true, true, Vector3( 0.0f, 0.0f, 0.0f ), TheWaterTransparency->m_minWaterOpacity ) == WW3D_ERROR_OK)
{
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DScene.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DScene.cpp
index 3eaf89f51..0600731ba 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DScene.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DScene.cpp
@@ -829,7 +829,7 @@ void RTS3DScene::renderOneObject(RenderInfoClass &rinfo, RenderObjClass *robj, I
rinfo.Pop_Override_Flags(); //flags used to disable base pass and only render custom heat vision pass.
}
-//DECLARE_PERF_TIMER(translucentRender)
+DECLARE_PERF_TIMER(translucentRender)
/**Draw everything that was submitted from this scene*/
void RTS3DScene::Flush(RenderInfoClass & rinfo)
@@ -862,7 +862,7 @@ void RTS3DScene::Flush(RenderInfoClass & rinfo)
flushTranslucentObjects(rinfo); //draw all translucent meshes which don't need per-poly sorting.
{
- //USE_PERF_TIMER(translucentRender)
+ USE_PERF_TIMER(translucentRender)
//don't draw transparent in this mode because they interfere with destination alpha
if (m_customPassMode == SCENE_PASS_DEFAULT && Get_Extra_Pass_Polygon_Mode() == EXTRA_PASS_DISABLE)
@@ -950,10 +950,10 @@ void RTS3DScene::updatePlayerColorPasses(void)
#define ZBias 0.0001f
-//DECLARE_PERF_TIMER(NonTerrainRender)
+DECLARE_PERF_TIMER(NonTerrainRender)
void RTS3DScene::Render(RenderInfoClass & rinfo)
{
- //USE_PERF_TIMER(NonTerrainRender)
+ USE_PERF_TIMER(NonTerrainRender)
DX8Wrapper::Set_Fog(FogEnabled, FogColor, FogStart, FogEnd);
//Override the behind building selection if it's not available on current hardware (needs stencil).
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DShroud.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DShroud.cpp
index e5c25e718..f45a60619 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DShroud.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DShroud.cpp
@@ -521,7 +521,7 @@ TextureClass *DummyTexture=NULL;
//#define LOAD_DUMMY_SHROUD
//-----------------------------------------------------------------------------
-//DECLARE_PERF_TIMER(shroudCopy)
+DECLARE_PERF_TIMER(shroudCopy)
//-----------------------------------------------------------------------------
/** Updates video memory surface with currently visible shroud data */
@@ -714,7 +714,7 @@ void W3DShroud::render(CameraClass *cam)
}
{
- //USE_PERF_TIMER(shroudCopy)
+ USE_PERF_TIMER(shroudCopy)
DX8Wrapper::_Copy_DX8_Rects(
m_pSrcTexture,
&srcRect,
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp
index 29008757c..82041d108 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp
@@ -1571,10 +1571,10 @@ void WaterRenderObjClass::renderMirror(CameraClass *cam)
* This algorithm doesn't apply to translucent water, which is rendered into a
* texture and rendered at end of scene. */
//-------------------------------------------------------------------------------------------------
-//DECLARE_PERF_TIMER(Water)
+DECLARE_PERF_TIMER(Water)
void WaterRenderObjClass::Render(RenderInfoClass & rinfo)
{
- //USE_PERF_TIMER(Water)
+ USE_PERF_TIMER(Water)
if (TheTerrainRenderObject && !TheTerrainRenderObject->getMap())
return; //no map has been loaded yet.