Learning more from your debug output

Learning more from your debug output

In the context Nick Hodges’s post on memory usage, here are some tweaks for OutputDebugString which I’ve been using for a few years to help debug trace live services running in production environment.  The memory consumption code looks like the spitting image of the stackoverflow post, so I probably gleaned it from there, or possibly from 

http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/devcommon/monitormemorymanager_xml.html.

or the MemoryManager usage tracker sample:

http://sourceforge.net/p/radstudiodemos/code/HEAD/tree/branches/RadStudio_XE4/Delphi/RTL/Usage%20Tracker/MemoryManagerUsageTracker.pas

If you peruse the documentation –

http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/devcommon/monitormemorymanager_xml.html

and

http://docwiki.embarcadero.com/RADStudio/XE4/en/Monitoring_Memory_Usage

also give hints about GetMemoryMap which supposedly helps you track memory for the entire process, in case you have sub-processes or COM stuff to deal with.  

I haven’t dabbled there, though.

unit CustomDebugOut;

// Lars Fosdal

interface

uses

  Windows, SysUtils, DateUtils;

  procedure OutputDebugString(aStr:PChar); Inline; overload;

  procedure OutputDebugString(const aStr:String); Inline; overload;

  function CurrentThreadId:String; Inline;

  function CurrentTime:String; Inline;

  function MemoryUsed: cardinal; Inline;

implementation

function CurrentThreadId:String; Inline;

begin

  Result := IntToStr(GetCurrentThreadId);

end;

function CurrentTime:String; Inline;

begin

  Result := FormatDateTime(‘hh:nn:ss,zzz ‘, Now);

end;

function MemoryUsed: cardinal; Inline;

var

  MMS: TMemoryManagerState;

  Block: TSmallBlockTypeState;

begin

  GetMemoryManagerState(MMS);

  Result := MMS.TotalAllocatedMediumBlockSize + MMS.TotalAllocatedLargeBlockSize;

  for Block in MMS.SmallBlockTypeStates

   do Result := Result + (Block.UseableBlockSize * Block.AllocatedBlockCount);

  Result := Result DIV 1024;

end;

procedure OutputDebugString(aStr:PChar); Inline;

begin

  Windows.OutputDebugString(pChar(‘{‘

   + CurrentTime                       // time

   + ‘(‘+CurrentThreadId+’)’           // thread

   + ‘ ‘+ IntToStr(MemoryUsed) +’k’   // memory in k

   + ‘} ‘ + aStr));

end;

procedure OutputDebugString(const aStr:String); inline;

begin

  OutputDebugString(pChar(aStr));

end;

end.

—-

Leave a Reply