How to measure Performance by using High Resolution Timer in Visual C++?

31 03 2009


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 Set Console Text Color?

29 03 2009


Getting bored with the black and white console? Did you ever wish to change the text or background color of console?

setconsoletextcolor
Image Courtesy – reginadowntown.


Yes! You can use the api – SetConsoleTextAttribute(). See the code snippet below.

// Set text color as Yellow with white background.
SetConsoleTextAttribute(
    GetStdHandle( STD_OUTPUT_HANDLE ),
    FOREGROUND_INTENSITY              | // Set Text color
    FOREGROUND_RED | FOREGROUND_GREEN | // Text color as Yellow.
    BACKGROUND_INTENSITY              | // Set Background color
    BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE ); // White Bg.


Please note that you can mix red/green/blue constants to make new colors. Have fun. 🙂


Targeted Audience – Beginners.





Happy Birthday! WeSeeTips!!!

25 03 2009

birthday2
Image Courtesy – Corbis

Dear Visual C++ Enthusiasist,

Today is the first birthday of WeSeeTips. When i start this blog, my dream target was 1000 hits and at least 10-20 visitors per day. But at present, weseetips have 1,20,000 hits and more than 500~600 daily visits! Thanks a lot for making weseetips a grand success! All the credit goes to my fellow readers – that means you! Without you, this couldn’t be achieved. My sincere thanks to you all for reading weseetips and for keep watching! Lets grow together!

I would like to have a feedback from your side. About positives and negatives, points to improve, etc.. Kindly spend few seconds to drop some words! Please Help me to help you!

Very soon WeSeeTips will have a cosmetic change over! Well, whats it? Shhhhh! that’s a secret. 😉 Keep watching buddy, that day is not so far. Once again thanking you all,

For WeSeeTips,
Jijo.





How to Pass Array by Reference?

15 03 2009


We used to use arrays, a lot. But did you ever tried how to pass array by reference to another function? Yes. Its a bit tricky.

arraybyreference


Receiving arrays by reference have special syntax. The arrayname and & symbol should be enclosed in parenthesis. And you should specify the size of array. Have a look at the following code snippet.

// Receive Array by reference.
void GetArray( int (&Array) [10] )
{
}

// Test array by reference.
void CRabbitDlgDlg::TestArray()
{
    // Pass array by reference.
    int Array[10] = { 0 };
    GetArray( Array );
}


Indeed, you can pass the array as pointer and then use it. But if you ever need to pass an array by reference, then remember this tip.


Targeted Audience – Beginners.





How to blink LED’s in Keyboard?

12 03 2009


Do you remember those golden DOS days, where we access the video RAM directly and set the status of NumLock, ScrollLock etc and blink the LED of keyboard. Now in modern windows environment we are no more allowed to access the video RAM directly. But is there any way to blink the keyboard LEDs as we did before?

keyboardblinking


Yes. The trick is to send NumLock keystroke event by using keybd_input() function. See the sample code snippet from MSDN.

// Set NUMLOCK Status.
void SetNumLock( BOOL bState )
{
    BYTE keyState[256];

    GetKeyboardState((LPBYTE)&keyState);
    if( (bState && !(keyState[VK_NUMLOCK] & 1)) ||
        (!bState && (keyState[VK_NUMLOCK] & 1)) )
    {
        // Simulate a key press
        keybd_event( VK_NUMLOCK,
                     0x45,
                     KEYEVENTF_EXTENDEDKEY | 0,
                     0 );

        // Simulate a key release
        keybd_event( VK_NUMLOCK,
                     0x45,
                     KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP,
                     0);
    }
}

// Blink NUMLOCK.
void BlinkNumLock()
{
    // Blink status.
    bool bBlink = false;

    // Blink the NUMLOCK periodically.
    while( true )
    {
        SetNumLock( bBlink );
        bBlink = !bBlink;
        Sleep( 100 );
    }
}

You can also use SendInput(), which is the latest version of keybd_event() to simulate keystrokes.

And one more thing, I was searching for an image for this post, but couldn’t find a suitable one. And this image is suggested by my wife. 🙂 How is it? Did you like it? She would like to hear from you 😉


Targeted Audiance – Intermediate.





How to Assert on Object Slicing?

11 03 2009

What is Object Slicing?
If derived object is assigned to Base object, then the derived object will be sliced off and only the base part will be copied. Indeed it will cause abnormalities. But is there any mechanism, atleast to assert while object slicing?
objectslicing


You can do it by adding an overloaded constructor for derived in Base class and then assert in it. For instance,

// Forward Declaration.
class Derived;

// Base class.
class Base
{
public:
    // Default Constructor.
    Base() {}
    Base( Derived& derived ) { ASSERT( FALSE ); }
};

// Derived class.
class Derived
{
};
...

// Test code.
Base ObjBase;
Derived ObjDerived;

ObjBase = ObjDerived;


Take care that it won’t work for passing pointer and reference. But still good enough. nah?


Targeted Audiance – Intermediate.





How to set Font for Static Text Controls?

4 03 2009


By default, static text is displayed in normal fonts. And you don’t have any option to make it bold or italic or underline. Is there any way to enable these styles and change the font of the static text control?

staticfont


Yes! you can do it. First you’ve to get the current font of the text control and then enable the styles you need then set it back. Setting font is done in OnInitDialog() and new font is kept as member variable. See the code snippet below.

BOOL CStaticFontDlg::OnInitDialog()
{
	...

    // Get current font.
    CFont* pFont = GetDlgItem( IDC_STATIC_ITALIC )->GetFont();
    LOGFONT LogFont = { 0 };
    pFont->GetLogFont( &LogFont );

    // Create new font with underline style.
    LogFont.lfUnderline = TRUE;
    m_StaticFont.CreateFontIndirect( &LogFont );

	// Sets the new font back to static text.
    GetDlgItem( IDC_STATIC_ITALIC )->SetFont( &m_StaticFont );

	return TRUE;
}

Now the static text will look like this.

staticfont3


Don’t forget to change the Id of static text control from IDC_STATIC to something else. Or else GetDlgItem() will return invalid handle.


Targeted Audiance – Intermediate.