Posts tagged C++
How to measure Performance by using High Resolution Timer in Visual C++?
3![]()
Ever had a performance tweaking project? The first thing you need is a high resolution stop watch to measure performance of different code blocks. But is there a high resolution stop watch?

![]()
You can use QueryPerformanceCounter(). You can get the performance counter frequency – i.e. ticks per second by calling QueryPerformanceFrequency(). Have a look at the sample CStopWatch class.
// Stop watch class.
class CStopWatch
{
public:
// Constructor.
CStopWatch()
{
// Ticks per second.
QueryPerformanceFrequency( &liPerfFreq );
}
// Start counter.
void Start()
{
liStart.QuadPart = 0;
QueryPerformanceCounter( &liStart );
}
// Stop counter.
void Stop()
{
liEnd.QuadPart = 0;
QueryPerformanceCounter( &liEnd );
}
// Get duration.
long double GetDuration()
{
return ( liEnd.QuadPart - liStart.QuadPart) /
long double( liPerfFreq.QuadPart );
}
private:
LARGE_INTEGER liStart;
LARGE_INTEGER liEnd;
LARGE_INTEGER liPerfFreq;
};
int main()
{
// Stop watch object.
CStopWatch timer;
// Start timer.
timer.Start();
// ZZzzzzz... for few seconds.
Sleep( 3000 );
timer.Stop();
// Get the duration. Duration is in seconds.
long double duration = timer.GetDuration();
return 0;
}
![]()
Even if the sample app slept for 3 seconds, in high resolution timer, the duration is 2.9xxx seconds.
Can you guess why?
![]()
Targeted Audiance – Intermediate.
Function call by using null pointer will crash?
3![]()
Crash on function call by using null pointer – The ultimate C++ Nirvana.
Whether function call by null pointer always crash? Is it possible to call functions by using null pointer without crash? Check the following code snippet. Whether it will crash?
// Console Helper class.
class ConsoleHelper
{
public:
// Prints a line to console.
void PrintLine()
{
cout << "---------------" << endl;
}
};
// The one and only one Main.
int main(int argc, char* argv[])
{
// Call the function by using null pointer.
ConsoleHelper* pConsoleHelper = 0;
pConsoleHelper->PrintLine();
return 0;
}
![]()
It won’t crash. Because in the function call we’re not accessing any member variables. Function call by using null pointers crash only if we’re accessing some member variables. Its because for every object function call, the object address is pushed to the function stack as “this” pointer. If the object pointer is null, then the “this” pointer also become null and hence the crash!
![]()
Null pointers are not that much bad! isn’t it?
![]()
Targeted Audience – Intermediate.
Use printf() while tracing from multithreaded console applications.
2![]()
Usually most of our back end server applications might be multi-threaded console applications which contain several threads running simultaneously. Usually we do trace issues by printing strings to console screen by using cout or printf(). As a general practice, we usually stick upon cout because of our affinity towards C++.
But there is a great pitfall lies behind.
![]()
If you use cout, you can see the traces are shuffled and displayed only after certain interval. This is because, cout uses buffered output. So if you need real time tracing, use printf().
if you still want to use cout, then flush the streams by calling flush(). See the code snippt.
// Trace the message. cout << _T( "Tracing from thread" ); // flush the buffer. cout.flush();
![]()
This difference may not be visible if you are running one thread at a time. If you have a number of threads and each one is busy in dumping traces, definitely you can see this.
![]()
Targeted Audience – Intermediate.
Function Objects or simply Functors.
0![]()
A function object is an ordinary class object with operator () overloaded. The specialty of functor is that the object can also act as function calls. But the power of a functor is – it can hold state.
![]()
See a sample code snippet for implementing a functor which compares two strings – with and with out case sensitive.
class Compare
{
public:
// Constructor.
Compare()
: m_CaseSensitive(true)
{}
// overloaded () operator.
BOOL operator()( CString& csString1, CString& csString2)
{
if( m_CaseSensitive )
{
// Case sensitive comparison.
return csString1 == csString2;
}
else
{
// Non Case sensitive comparison.
return (csString1.CompareNoCase( csString2 ) == 0) ? TRUE : FALSE;
}
}
// Set the comparison.
void SetComparisonCaseSensitive( bool CaseSensitive )
{ m_CaseSensitive = CaseSensitive; }
private:
bool m_CaseSensitive;
};
void CompareStrings()
{
CString csString1 = _T("Hello");
CString csString2 = _T("hello");
// The functor.
Compare CompareStrings;
// Demo of case sensitive comparison.
BOOL bCaseSensitiveComparison = CompareStrings( csString1,
csString2);
// non Case sensitive comparison.
CompareStrings.SetComparisonCaseSensitive( false );
// Demo of case sensitive comparison.
BOOL bNonCaseSensitiveComparison = CompareStrings( csString1,
csString2);
}
In the code snippet, a string comparison is implemented by using a functor. Ideally if you want the string comparison to be able to handle both case sensitive and non-case sensitive comparisons, you’ve to use some boolean values globally or should pass it as function parameters. Or else you’ve to implement two different functions to implement both of them.
Here comes the real power of a functor. Since Its a class, can hold parameters. So that you can avoid global variables, may be some function parameters etc. Try functors… its fun!
![]()
Don’t think that functors is a new feature introduced by C++. Functors exists long before the days of C++
One of the early languages that implemented functors was SmallTalk.
![]()
Targeted Audience – Intermediate.
How to hook memory allocation failures by malloc()?
1![]()
C have malloc() and C++ have more advanced “new” for allocating memory. One of the advantages of new over malloc is that its tailored to report memory allocation failures where malloc() is not. For instance, in C++ we can set a “Allocation failure handler” function by calling _set_new_handler(). When ever “new” fails to allocate function, this function will be called. Its a nice feature that malloc() don’t have by default.
There are several maintenance projects which are actually done in C but ported to C++. Usually instead of rewriting entire source, the legacy code exists in C itself and new feature additions will be done in C++, since they co-exist with each other. So in the old C code base, the malloc() will be used extensively. So hooking memory failures by malloc() are necessary and how can we do it?
![]()
By default malloc() won’t call the New Handler function during memory failure. But you can specify to do so by calling _set_new_mode(). See the sample code snippet below.
#include "new.h"
// Memory Allocation Failure Handler.
int AllocationFailureHandler( size_t )
{
// Do what ever you wish.
return 0;
}
// The one and only Main.
void main()
{
// Set the NewHandler and try "new" allocation failures.
// The NewHandler will be called.
_set_new_handler( AllocationFailureHandler);
char* pAllocatedByNew = new char[1000000000000];
// Check malloc. By default it won't call
// newHandler on failure.
char* pAllocatedByMalloc = (char*)malloc( 1000000000000 );
// Enable allocation failure reporting for malloc.
// and try once again. This time, NewHandler is called!
_set_new_mode( 1 );
pAllocatedByMalloc = (char*)malloc( 1000000000000 );
}
Now hook the memory allocation failures from you legacy code too…
![]()
If you have MFC support, then the NewHandler provided by you will be overridden and that of MFC will handle the allocation failure. So take care…
And _set_new_mode() is not the part of C++ language standard. Its Microsoft specific.
![]()
Targeted Audiance – Intermediate.
auto_ptr as pass by value to functions – you are going to face a crash.
0![]()
Memory leaks are our nightmare and auto_ptr’s are used for making our life easier which does automatic memory deletion. If a pointer is assigned to an auto_ptr, it will be deleted when the auto_ptr went out of scope. But use this automatic deletion carefully, especially while passing it as function arguments by value. You are going to face a crash!
![]()
The problem is “owership”. Every auto_ptr holds an ownership flag. when an auto_ptr is assigned to another auto_ptr, the ownership flag is transfered from first to second. And only the auto_ptr with ownership flag enabled, can delete the resource. This method is used to avoid multiple deletion of the same pointer kept by several auto_ptrs. There will be only one owner auto_ptr at a time.
Now when you pass the auto_ptr by value, actually, you are passing the owner ship to the stack variable of the called function. Now the stack parameter will become the owner of your pointer and when the function returns, the auto_ptr in stack will be destructed and since its the owner, it will delete your passed pointer. When you access you main auto_ptr, then you’ll probably get a crash!!! See the code snippet for an e.g.
// Function which receives auto_ptr as value.
void ToUpper( auto_ptr<CString> pString )
{
// Shows the messageBox.
pString->MakeUpper();
}
// The one and only Main.
void main()
{
// An auto_ptr which holds a CString.
auto_ptr<CString> pString(
new CString(_T("Hello AutoPtr")));
// Make the string upper case by
// passing it as value.
ToUpper( pString );
// At this point, your CString is already
// been deleted by the stack variable in function.
// Now change the string to Lower and face the crash!!!
pString->MakeLower();
}
![]()
You can make the situation safe by passing by reference. While doing so, only a reference is passed to the stack variable and hence the ownership remains in you main auto_ptr itself.
![]()
Targeted Audience – Intermediate.
Seek uniqueness? Use STL set.
3![]()
In several conditions we’ve to worry about avoiding duplicate data. For instance, if you have a combo-box which contains browsed file paths as history, it will be nice to avoid multiple occurrence of same file path. In those cases you can make use of STL set to remove duplicate data.
![]()
Set is a template class like any other STL container. For adding new data to set, you’ve to call insert() and for iterating you can use iterators. See sample code snippet below.
#include "set"
#include "string"
using namespace std;
...
// Set which is used to hold FilePaths as strings.
set<string> FilePathSet;
// I am inserting the same path a number of times.
// But finally, while iterating you can see only one
// copy of the same data.
FilePathSet.insert("C:\Windows\System32");
FilePathSet.insert("C:\Windows\System32");
FilePathSet.insert("C:\Windows\System32");
FilePathSet.insert("C:\Windows\System32");
// Iterate through the set.
set<string>::iterator FilePathSetItr = FilePathSet.begin();
while( FilePathSetItr != FilePathSet.end())
{
// The unique data. Use it.
string UniqueFilePath = *FilePathSetItr;
// Increment to next item in set.
++FilePathSetItr;
}
![]()
Targeted Audience – Beginners.
How to update bulk amount of data to GUI controls without flicker.
0![]()
Usually for Listbox and Tree control, may be you need to add and delete thousands of entries. While doing so, its obvious that the control will flicker. It might be annoying to the user. So how can you avoid it?
![]()
You can use the api – LockWindowUpdate() and UnlockWindowUpdate() for remove the flicker while updating the UI. If a window is locked by calling LockWindowUpdate(), the the further call for getting the device context will return one with empty visible region. When you call UnlockWindowUpdate(), system invalidates the area and will send WM_PAINT. The WM_PAINT will be send only if some drawing is done to the window after locking.
You can download sample from here, which shows the difference.
See sample code snippet below.
// Lock the EditBox.
m_EditBox.LockWindowUpdate();
// Add any number of strings to it.
for( DWORD Index = 0; Index < 5000; ++Index )
{
CString csMessage;
csMessage.Format( _T("Item %d"), Index );
m_EditBox.AddString( csMessage );
}
// After updating, unlock it.
m_EditBox.UnlockWindowUpdate();
![]()
Please note that, only one window can be locked at a time.
![]()
Targeted Audience – Beginners.
Name Mangling – How to Undecorate a decorated C++ function name.
11![]()
For generating unique function names C++ decorates the function names to wired form. This is best known as Name Mangling. You can see sample of decorated function names by using dependency walker. Open any DLL in dependency walker and in the exported section, most probably you can see a list of decorated function names.
![]()
So, if you want to see the real function prototype of that decorated function name, what to do? Just use, UnDecorateSymbolName() function. Please see the following code block.
// Buffer for undecorating Function Name.
TCHAR tchUnDecoratedName[ 512 ];
// The Decorated function Name.
TCHAR tchDecoratedName[] =
_T( "?classCDataPathProperty@CDataPathProperty@@2UCRuntimeClass@@B" );
if( UnDecorateSymbolName( tchDecoratedName, // Decorated Name.
tchUnDecoratedName, // UnDecorated Name.
512, // Buffer size.
UNDNAME_COMPLETE )) // Flags.
{
// Display the undecorated function name.
CString csUndecoratedName( tchUnDecoratedName );
AfxMessageBox( csUndecoratedName );
}
![]()
Don’t forget to include the header file – “Dbghelp.h” and library file – “Dbghelp.lib“.
![]()
Targeted Audience – Intermediate.