Posts tagged Visual 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?

highperformancetimer


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.

How to share data between different instance of same DLL?

3


Usually Dlls are loaded into its corresponding process address space. Indeed the code is shared between all instances but not the global data. So the issue that we might face is – how can we share common data between all dll instances?


You’ve to declare your own shared data segment in your dll. You can use #pragma data_seg() to declare your own data segment. See the sample code snippet below.

#pragma data_seg (".MYSEG")
    int g_nInteger = 0;
    char g_szString[] = "hello world";
#pragma data_seg()

// Tell the linker that the section
// .MYSEG is readable, writable and is shared.
#pragma comment(linker, "/SECTION:.MYSEG,RWS")

Here we are declaring our data segment and are telling that, this segment is RWS – readable, writable and shared. This way we manage to share this data segment between all dll instances.


Targeted Audience – Intermediate.

How to set title for your console application window.

9


In huge frameworks, there might be a number of back-end servers running. Since they are servers most of them might be implemented as windows console applications to avoid gui overheads. But when you run the console, the title of the console window will be the path of console.exe.

Since there can be multiple console applications, One of the headache is to identify which console window is the server you are searching for? Usually we print logs in console such as “Image Server Started…” to identify which server it is. It will be nice, if we can set the console window title our own. So that we can easly identify the server application.


You can use the function – SetConsoleTitle(). Its straight forward. Just call the function by passing the preferred console title. See the code snippet below.

int main(int argc, char* argv[])
{
    // Set the console title of my Image Server.
    SetConsoleTitle( "Image Server." );

    // Let me see the result.
    getchar();
    return 0;
}


The SetConsoleTitle() is declared in wincon.h. But you just include windows.h which includes everything. ;)


Targeted Audience – Beginners.

How to Iterate all running process in your system.

3


In your system there might be several process running at the same time. So how to iterate through the running process in your system and get their infos?


You can use ToolHelp library for iterating and getting process information. First you’ve to take a snapshot of running process at that moment by calling CreateToolhelp32Snapshot(). Then you should iterate each process info by calling Process32First() and Process32Next(). See the code snippet below.

#include <tlhelp32.h>
    ...
// Get the process list snapshot.
HANDLE hProcessSnapShot = CreateToolhelp32Snapshot(
                                        TH32CS_SNAPALL,
                                        0 );

// Initialize the process entry structure.
PROCESSENTRY32 ProcessEntry = { 0 };
ProcessEntry.dwSize = sizeof( ProcessEntry );

// Get the first process info.
BOOL Return = FALSE;
Return = Process32First( hProcessSnapShot,
                         &ProcessEntry );

// Getting process info failed.
if( !Return )
{
    return;
}

do
{
    // print the process details.
    cout << _T("Process EXE File:") << ProcessEntry.szExeFile
                                    << endl;
    cout << _T("Process ID:") << ProcessEntry.th32ProcessID
                              << endl;
    cout << _T("Process References:") << ProcessEntry.cntUsage
                                      << endl;
    cout << _T("Process Thread Count:") << ProcessEntry.cntThreads
                                        << endl;

    // check the PROCESSENTRY32 for other members.
}
while( Process32Next( hProcessSnapShot, &ProcessEntry ));

// Close the handle
CloseHandle( hProcessSnapShot );


Together with process info, you can also get information regarding – Modules, Heaps, threads using these ToolHelp library functions. have a look at MSDN.


Targeted Audience – Intermediate.

CRT Debug support – The Magic Memory values.

2


Memory corruptions are every programmer’s nightmare. But Debug Heap provides some facility in debug build to help you to get rid of those memory corrupting problems. Depending to the type of memory allocation we have done, the debug heap will fill some magic value for the allocated memory contents. Take care that, this will be available only in debug build. Please see below.

  1. 0xCD – The memory locations filled with this magic number are allocated in heap and is not initialized.
  2. 0xFD – This magic number is known as “NoMansLand”. The debug heap will fill the boundary of the allocated memory block will this value. If you are rewriting this value, then it means, you are beyond an allocated memory block.
  3. 0xCC – The memory locations filled with this magic number means, it’s allocated in stack but not initialized. You can see this when you a variable on stack and look at its memory location. You can use /GZ compiler option to get the same feature in release build.
  4. 0xDD – The memory locations filled with this magic number are Released heap memory.


Regarding the 4th one – 0xDD, when I tried, the deleted memory locations are filled with 0xFEEE. I’ve to check it further. as per documentation its 0xDD.


Targeted Audience – Intermediate.

How to create NTFS File links Programmatically.

0


Unix guys don’t need an introduction about file links, because its one of the beginner Unix skills – how to create a file link. But usually in windows arena, file links may be the least discussed one among beginners. In simple words, file links are – one Physical file in disk but with different file names. All the file names points to the same file. There are a number of usages for file links.

  • Hide the master file from a bunch of naughty users.
  • You can assign different access rights for different users by creating file links for the same file.( each link have different permissions.)
  • To keep the filename constant and you can change the mapping to another file.
  • Etc etc… it goes on.


So how can i create a link for a file? You can use the api – CreateHardLink(). See the sample code snippet below.

CreateHardLink( _T(“c:\\masterfile.dat”),    // Source File
                _T(“c:\\LinkToMaster.dat”),  // Link name
                NULL );    // Security attributes


You can use DeleteFile() to delete the created link.


Targeted Audience – Beginners.

Use throw; carefully. Or else, Unhandled exception will be the result.

0


Usually throw; is used to rethrow the exception object. But you should be careful. If you call throw; where there is no exception object in the context, then it will result an un-handled exception and abnormal program termination. The interesting part is that, even catch(…) cannot catch such exceptions.


See the sample code snippet below.

try
{
    throw;
}
catch( ... )
{
}

So take care next time.


Targeted Audience – Intermedite.

How to find the source filename and line no. from memory pointer in debug version.

2


It will be nice, if its possible to find out the source filename and line number where the pointer is allocated by just using the memory pointer itself. Yes its possible! But only in debug version.


When you call new, the c runtime library allocates the memory and returns the pointer. But infront of the given pointer, one CRT MemoryBlock Header is secretly kept in debug version. see the declarations of Debug MemoryBlock header below.

typedef struct _CrtMemBlockHeader
{
struct _CrtMemBlockHeader * pBlockHeaderNext;
struct _CrtMemBlockHeader * pBlockHeaderPrev;
char *                      szFileName;
int                         nLine;
size_t                      nDataSize;
int                         nBlockUse;
long                        lRequest;
unsigned char               gap[nNoMansLandSize];
} _CrtMemBlockHeader;

In this header, several information about the allocated memory block is available – such as size of memory block, source filename and line no. where the memory is allocated, whether the memory block currently in use etc etc.


From the pointer, access the MemoryBlock header. Then all these informations will be available. See the code snippet below.

// decleration of MemoryBlock header from CRT Source.
#define nNoMansLandSize 4
typedef struct _CrtMemBlockHeader
{
struct _CrtMemBlockHeader * pBlockHeaderNext;
struct _CrtMemBlockHeader * pBlockHeaderPrev;
char *                      szFileName;
int                         nLine;
size_t                      nDataSize;
int                         nBlockUse;
long                        lRequest;
unsigned char               gap[nNoMansLandSize];
} _CrtMemBlockHeader;

...

// Allocate some memory.
float* pFloat = new float[100];

// Get the memory block header.
_CrtMemBlockHeader* pMemoryBlockHeader =
    reinterpret_cast<_CrtMemBlockHeader*>( pFloat );
--pMemoryBlockHeader;

// Source File and location where the memory is allocated.
CString csSourceFileName = pMemoryBlockHeader->szFileName;
DWORD dwLineNumber = pMemoryBlockHeader->nLine;


The memory allocation is different in debug and release. isn’t it? ;)


Targeted Audience – Advanced.

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.

How to locate the source code which pops the error message – More easily.

2


While debugging huge code bases, unexpectedly some error messages can be popped up. Most probably we might be seeing it for the first time and don’t have any idea, from which location of the code base, the error message get fired. How to locate it easily?


Just follow the steps -

1) Start the project by F5.
2) Do the steps to make the error messagebox to be shown. Now the error message will be shown.
3) Now instead of clicking of in the error message, take debugger and click menu, Debug -> Break.
4) Now take Debug -> Threads to see the threads running in your application.
5) You can see one of your thread, which is paused in a messagebox showing routine.
6) Select that thread and click SetFocus, to focus that thread.
7) Now take the Call Stack by Alt+7 and iterate through it from top to bottom.
8 ) You see one familiar function? Yes! its the one which pops the error message. Now go and fix the bug ;)


You can also put a breakpoint by finding the memory address of the functions that can be used for showing error messages. But, if the application uses some custom dialogs, then you’ve to put more effort. This method is the handy one with least headaches. Try it!


Targeted Audience – Beginners.

Go to Top