Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8658709
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T15:50:05+00:00 2026-06-12T15:50:05+00:00

What I would like to do is write a small program that continuously live

  • 0

What I would like to do is write a small program that continuously live counts the number of context switches that a specific process experiences per a sufficiently small unit of time. I have observed this functionality within the software “Process Explorer”, so I know it is definitely possible.

Unfortunately, I have very little idea of how to begin coding this and have so far been unable to find any helpful code snippets online. Thus, a small working example implementing a per process and per unit time live context switch count would be immensely helpful for me.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T15:50:06+00:00Added an answer on June 12, 2026 at 3:50 pm

    Here’s one way to do it – This will print the amount of context switches used by thread 0 of notepad (you can substitute any process and thread number you want in the CounterPathBuffer initialization) every second:

    #include "stdafx.h"
    #include <iostream>
    #include <windows.h>
    #include <stdio.h>
    #include <conio.h>
    #include <pdh.h>
    #include <pdhmsg.h>
    
    #pragma comment(lib, "pdh.lib")
    using namespace std;
    CONST ULONG SAMPLE_INTERVAL_MS    = 1000;
    CONST PWSTR BROWSE_DIALOG_CAPTION = L"Select a counter to monitor.";
    
    void wmain(void)
    {
        PDH_STATUS Status;
        HQUERY Query = NULL;
        HCOUNTER Counter;
        PDH_FMT_COUNTERVALUE DisplayValue;
        DWORD CounterType;
        SYSTEMTIME SampleTime;
        PDH_BROWSE_DLG_CONFIG BrowseDlgData;
        WCHAR CounterPathBuffer[PDH_MAX_COUNTER_PATH] = L"\\\\ComputerNameGoesHere\\Thread(notepad/0)\\Context Switches/sec";
    
    
        //
        // Create a query.
        //
    
        Status = PdhOpenQuery(NULL, NULL, &Query);
        if (Status != ERROR_SUCCESS) 
        {
           wprintf(L"\nPdhOpenQuery failed with status 0x%x.", Status);
           goto Cleanup;
        }
    
        //
        // Initialize the browser dialog window settings.
        //
    
    
    
        ZeroMemory(&BrowseDlgData, sizeof(PDH_BROWSE_DLG_CONFIG));
    
        BrowseDlgData.bIncludeInstanceIndex = FALSE;
        BrowseDlgData.bSingleCounterPerAdd = TRUE;
        BrowseDlgData.bSingleCounterPerDialog = TRUE;
        BrowseDlgData.bLocalCountersOnly = FALSE;
        BrowseDlgData.bWildCardInstances = TRUE;
        BrowseDlgData.bHideDetailBox = TRUE;
        BrowseDlgData.bInitializePath = FALSE;
        BrowseDlgData.bDisableMachineSelection = FALSE;
        BrowseDlgData.bIncludeCostlyObjects = FALSE;
        BrowseDlgData.bShowObjectBrowser = FALSE;
        BrowseDlgData.hWndOwner = NULL;
        BrowseDlgData.szReturnPathBuffer = CounterPathBuffer;
        BrowseDlgData.cchReturnPathLength = PDH_MAX_COUNTER_PATH;
        BrowseDlgData.pCallBack = NULL;
        BrowseDlgData.dwCallBackArg = 0;
        BrowseDlgData.CallBackStatus = ERROR_SUCCESS;
        BrowseDlgData.dwDefaultDetailLevel = PERF_DETAIL_WIZARD;
        BrowseDlgData.szDialogBoxCaption = BROWSE_DIALOG_CAPTION;
    
        //
        // Add the selected counter to the query.
        //
    
    
        Status = PdhAddCounter(Query, CounterPathBuffer, 0, &Counter);
        if (Status != ERROR_SUCCESS) 
        {
            wprintf(L"\nPdhAddCounter failed with status 0x%x.", Status);
            goto Cleanup;
        }
    
        //
        // Most counters require two sample values to display a formatted value.
        // PDH stores the current sample value and the previously collected
        // sample value. This call retrieves the first value that will be used
        // by PdhGetFormattedCounterValue in the first iteration of the loop
        // Note that this value is lost if the counter does not require two
        // values to compute a displayable value.
        //
    
        Status = PdhCollectQueryData(Query);
        if (Status != ERROR_SUCCESS) 
        {
            wprintf(L"\nPdhCollectQueryData failed with 0x%x.\n", Status);
            goto Cleanup;
        }
    
        //
        // Print counter values until a key is pressed.
        //
    
        while (!_kbhit()) 
        {
            Sleep(SAMPLE_INTERVAL_MS);
    
            GetLocalTime(&SampleTime);
    
            Status = PdhCollectQueryData(Query);
            if (Status != ERROR_SUCCESS) 
            {
                wprintf(L"\nPdhCollectQueryData failed with status 0x%x.", Status);
            }
    
            wprintf(L"\n\"%2.2d/%2.2d/%4.4d %2.2d:%2.2d:%2.2d.%3.3d\"",
                    SampleTime.wMonth,
                    SampleTime.wDay,
                    SampleTime.wYear,
                    SampleTime.wHour,
                    SampleTime.wMinute,
                    SampleTime.wSecond,
                    SampleTime.wMilliseconds);
    
            //
            // Compute a displayable value for the counter.
            //
    
            Status = PdhGetFormattedCounterValue(Counter,
                                                 PDH_FMT_DOUBLE,
                                                 &CounterType,
                                                 &DisplayValue);
            if (Status != ERROR_SUCCESS) 
            {
                wprintf(L"\nPdhGetFormattedCounterValue failed with status 0x%x.", Status);
                goto Cleanup;
            }
    
    
            wprintf(L",\"%.20g\"", DisplayValue.doubleValue);
        }
    
    Cleanup:
    
        //
        // Close the query.
        //
    
        if (Query) 
        {
           PdhCloseQuery(Query);
        }
    
        int x;
        cin >>x;
    }
    

    Most of the code is from this source: msdn.microsoft.com/en-us/library/aa371886%28v=vs.85%29.aspx. I would like to shorten the amount of time between consecutive checks on the context switches (make it less than a second). If anyone has any ideas as to how to do this, that’d be great.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I would like to write a small tool that takes a C++ program (a
I would like to write a small piece of program that launches threads, consumes
I would like to write a small program that will run other programs. I'm
I would like to write a small program simulating many particle collisions, starting first
I would like to write a small Google Chrome extension in which I use
I would like to write a function that creates a plot of a set
I would like to write an if statement that would continue to repeat a
I would like to write a query that returns a single date value, that
I would like to write a cross-platform function in C++ that contains system calls.
I would like to write an if statement that will do something base on

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.