MATLAB, Visual Studio and Windows11 Pro
Me:
I mean by compatibility is the speed when running a script, I found that the older machine of lower
capabilities and windows10 runs that code faster?
Google:
It makes total sense why you are experiencing this. It is a very common issue when trying to run
older software on cutting-edge hardware and newer operating systems
Your modern Windows 11 machine is likely running slower because of how Windows 11 manages
modern processor architectures and how legacy MATLAB utilizes execution engines. Here are the
hidden culprits slowing your script down, alongside how to fix them:
Why it's slower on a stronger machine:
The Intel/AMD Hybrid Architecture Trap (E-Cores): Most modern multi-core processors use a
mix of Performance Cores (P-cores) and Efficiency Cores (E-cores). Because MATLAB R2014a
is completely blind to this modern layout, Windows 11 often assumes an unrecognized legacy app
is a low-priority background process. It shunts MATLAB directly onto your slowest, lowest-power
E-cores.
The "Minimized Window" Penalty: Windows 11 aggressively throttles resources for background
apps. If you minimize MATLAB or click onto another window while your script is running,
Windows 11 will automatically starve it of CPU power, dropping execution speeds drastically.
The Old JIT (Just-In-Time) Engine: MATLAB introduced a massive overhaul to its execution
engine in R2015b (the LXE engine), which allows scripts to utilize modern CPU instruction sets.
R2014a relies on an old JIT compiler that cannot exploit the architectural upgrades of your new
processor.
How to reclaim your speed on Windows 11
Try these tweaks in order to force Windows 11 to give R2014a the processing power it deserves:
1. Change Windows Power Plan to "Best Performance" By default, Windows 11 balances
power consumption, which heavily limits legacy apps. Open Windows Settings (Win + I)
→ System → Power \& Battery. Change the Power Mode dropdown from Balanced to Best
Performance.
2. Keep the MATLAB Window Focused and Maximized: Because of Windows 11's
aggressive background sleep cycles, do not minimize the MATLAB window while your
script runs. Leave it open on your main screen (or a secondary monitor) as the active,
highlighted window to force Windows to use your fast P-cores.
3. Manually Force MATLAB onto Performance Cores (Affinity):
You can manually override Windows 11 and force MATLAB to use your fastest CPU cores:
1.Start MATLAB R2014a.
2.Press Ctrl + Shift + Esc to open the Task Manager.
3.Go to the Details tab on the left sidebar.
4.Find matlab.exe, right-click it, and select Set affinity.
5. Uncheck the last few CPU cores (which are usually the slow E-cores)
or simply assign it to specific primary cores like CPU 0, 1, 2, 3.
6. Click OK.
4. Run MATLAB in a Windows 10 Virtual Machine
If the steps above don't fully close the performance gap, using your Windows 11 Pro Hyper-V
feature to run a lean Windows 10 virtual environment will return the script to its normal native
speed. The older environment won't aggressively throttle the R2014a engine.
Google:
To help pinpoint the issue, what kind of operations does your script focus on (e.g., heavy loops,
matrix multiplications, or graphics/plotting)? Also, what CPU is in your new machine? Knowing
this can help find the ideal configuration.
Me:
My current CPU is core i7 1255U.
Google:
Your Intel Core i7-1255U perfectly explains the exact performance drop you are seeing.
This processor uses a highly asymmetric hybrid architecture designed specifically for battery
saving. It has a total of 10 cores, but they are split unevenly:
2 Performance Cores (P-Cores): Very fast, heavy lifters.
8 Efficiency Cores (E-Cores): Very slow, low-power cores meant for background tasks (like
checking emails).
Because MATLAB R2014a was created 8 years before this CPU architecture existed, it cannot
communicate with the Intel Thread Director. Windows 11 sees an ancient application running a
heavy loop, misinterprets it as a background process, and dumps the entire MATLAB script onto
your 8 slow E-Cores.
Here is exactly how to pin MATLAB to your P-Cores to fix the speed issue:
Step-by-Step Fixes for the i7-1255U:
1. Pin MATLAB to CPU Cores 0, 1, 2, and 3 (Task Manager Affinity):
On your specific i7-1255U processor, the first 4 virtual threads belong to your fast P-Cores. The
rest belong to the slow E-Cores.
1.
2.
3.
4.
5.
6.
7.
Open MATLAB R2014a and start your script.
Press Ctrl + Shift + Esc to open the Task Manager.
Click the Details tab on the left sidebar.
Find matlab.exe in the list, right-click it, and select Set affinity.
Uncheck All Processors.
Check ONLY CPU 0, CPU 1, CPU 2, and CPU 3.
Click OK.
Note: You will have to do this each time you launch MATLAB, as Windows resets affinity upon
closing the app.
2. Change Task Manager Priority to "High":
While you are still in the Details tab of the Task Manager:
1. Right-click matlab.exe.
2. Hover over Set priority and change it from Normal to High.
3. This forces Windows 11 to prioritize MATLAB's execution timing over other background
tasks.
3. Disable Java Threading Adjustments (For Loops)
If your script relies heavily on for or while loops, R2014a's old JIT compiler might be choking on
modern CPU hyper-threading. You can try disabling multithreading inside MATLAB to see if a
single P-core handles it faster:
-
In the MATLAB Command Window, type: maxNumCompThreads(1) and press Enter.
Run your script to see if the speed increases. (Type maxNumCompThreads('automatic') to
revert it).
Please try running your script after setting the affinity to CPU 0-3. Let me know if you notice an
immediate bump in execution speed or if it still lags behind the older machine!
Me:
Ok, now I want how to make the machine dedicated to computation while running a C++ source
code via visual studio IDE 2022.
Google:
To dedicate your Intel Core i7-1255U machine entirely to running and compiling your C++ code
in Visual Studio 2022, you need to use a completely different strategy than you did with MATLAB
R2014a.
Unlike legacy MATLAB, Visual Studio 2022 is fully optimized for Windows 11 and modern
hybrid CPUs. Instead of restricting it to just a few cores, you want to unleash its ability to use your
entire CPU (both P-Cores and E-Cores) for compiling, while configuring Windows to prioritize
your running C++ executable above all else.
Here is how to configure your system for maximum C++ computation performance:
1. Optimize the Visual Studio Compiler (Multi-Threaded Building)
Compiling C++ code can be incredibly resource heavy. You want Visual Studio to use every ounce
of your 10-core CPU during compilation.
Enable Multi-processor Compilation:
- Right-click your project in the Solution Explorer and select Properties.
- Navigate to C/C++ → General.
- Find Multi-processor Compilation and change it to Yes (/MP).
Enable Parallel Code Generation:
- In the same Properties window, go to C/C++ → Code Generation.
- Set Enable Parallel Code Generation to Yes (/Qpar). This allows the compiler to automatically
optimize your loops to run across multiple cores if possible.
2. Configure Windows for Background/Computational Priority (???? Very Risky)
By default, Windows 11 prioritizes the user interface (smooth animations, clicking windows). You
can change a deep Windows setting to prioritize raw processing power instead.
1. Press Win + R, type sysdm.cpl, and hit Enter to open System Properties.
2. Go to the Advanced tab.
3. Under the Performance section, click Settings....
4. Go to the Advanced tab in the new window.
5. Under Adjust for best performance of:, change the selection from Programs to Background
services.
6. Click Apply and OK.
Why does this help? This adjusts the Windows scheduler to give longer, uninterrupted CPU time
slices to heavy computational tasks rather than frequently pausing them to refresh the desktop
interface.
3. Automatically Boot the Executable into "High Priority"
When you execute your compiled C++ program, you want Windows to treat it as the most
important task on the computer.
Instead of manually using Task Manager every time, you can add a snippet of Windows API code
directly to the very beginning of your main() function in C++. This forces the program to request
maximum resources from the operating system the moment it launches:
#include <iostream>
#include <windows.h> // Required for Windows API
int main() {
// Force the OS to give this application High CPU Priority
SetPriorityClass(GetCurrentProcess(), HIGH\_PRIORITY\_CLASS);
// Your heavy computational code goes here...
std::cout << "Running at maximum priority!" << std::endl;
return 0;
}
4. Ensure Laptop Power Delivery (Crucial for "U" Series CPUs)
Your i7-1255U is a low-voltage processor. It is heavily constrained by power and heat limitations.
* Plug it in: Never run heavy C++ simulations on battery. The CPU will aggressively throttle its
speed to save juice.
* Elevate the laptop: Heavy computation will cause the CPU to heat up quickly. Once it hits its
thermal limit, it will slow down. Elevate the back of the laptop slightly or use a cooling pad to
keep the clock speeds high.
Me:
You meant that solution No.3 is analogue to manually force MATLAB into Performance Cores
(Affinity). Isn't it?
Google:
Not quite! Let's clarify the difference, because Windows manages programs using two distinct
concepts: Priority and Affinity.
The code snippet from Solution 3 (SetPriorityClass) is actually the automated version of setting
Priority to High, not setting the Affinity.
Here is the exact comparison of the manual Task Manager steps versus the automated C++ code:
Action in Task Manager:
1. Right Click → Set Priority → High
What it Does:
Tells Windows: "Give this program CPU time before other apps."
The Automated C++ Code Equivalent:
SetPriorityClass(GetCurrentProcess(), HIGH\_PRIORITY\_CLASS);
Action in Task Manager:
2. Right Click -> Set Affinity -> Select Cores 0-3
What it Does:
Tells Windows: "Only run this program on these specific physical CPU cores (P-Cores)."
The Automated C++ Code Equivalent:
SetProcessAffinityMask(GetCurrentProcess(), 0x0F);
The Core Difference (Priority vs. Affinity)
* Priority (Solution 3 code) decides WHEN your program gets to use the CPU. A high priority
means your C++ code doesn't have to wait in line behind Chrome, Discord, or Windows Update.
* Affinity (The MATLAB fix) decides WHICH physical cores the program is allowed to sit on.
For your i7-1255U, affinity is what keeps a program trapped on the fast P-Cores and blocks it from
drifting over to the slow E-Cores.
🛠How to do BOTH automatically in C++
If you want your C++ code to automatically get the High Priority and force itself onto the
Performance Cores (Affinity) exactly like we did for MATLAB, you include both lines at the top
of your main() function:
#include <iostream>
#include <windows.h>
int main() {
// 1. Automates "Set Priority -> High"
SetPriorityClass(GetCurrentProcess(), HIGH\_PRIORITY\_CLASS);
// 2. Automates "Set Affinity -> Cores 0, 1, 2, 3" (Your P-Cores)
// 0x0F is hexadecimal for the binary mask 00001111, which selects the first 4 CPU threads.
SetProcessAffinityMask(GetCurrentProcess(), 0x0F);
// Your computational code goes here...
return 0;
}
By adding both lines, you completely eliminate the need to ever open the Task Manager for your
C++ program. It will instantly claim the highest priority and lock itself exclusively to your fastest
cores the microsecond it boots up.
Would you like to know how to verify if the C++ code successfully locked itself to those P-cores
while it's running, or do you want to look into compiler optimization flags (like /O2 or /Ot) to
make the math operations themselves run faster?
Me:
How to do it manually in visual studio using task manager?
Google:
To do this manually using the Task Manager while running your code from Visual Studio 2022,
follow these steps: (??????Very Risky)
Step 1: Put a "Pause" at the start of your C++ code
Because compiled C++ programs execute incredibly fast, your program might finish before you
even have time to open the Task Manager. You need to temporarily force the program to pause at
the very beginning of main() so it stays open.
Add std::cin.get(); to the very top of your main function:
#include <iostream>
int main() {
std::cout << "Press ENTER to start the calculation..." << std::endl;
std::cin.get(); // <-- This pauses the program so you can use Task Manager
// Your heavy computation code goes here...
for(int i = 0; i < 1000000; i++) { /\* math \*/ }
return 0;
}
Step 2: Run the program from Visual Studio
1. Click the Local Windows Debugger button (or press F5 / Ctrl + F5) in Visual Studio to launch
your program.
2. The console window will pop up and display "Press ENTER to start the calculation...".
3. Do not press Enter yet. Leave the window open.
Step 3: Configure Priority and Affinity in Task Manager
1. Press Ctrl + Shift + Esc to open the Windows Task Manager.
2. Click on the Details tab on the left sidebar (the icon looks like a list with checkmarks).
3. Find your compiled C++ program in the list.
Note: If you are running in "Debug" mode, look for your project name (e.g., MyProject.exe). If
you can't find it, look for VSDebugConsole.exe which is the window hosting your program.
4. Set Priority: Right-click the .exe file → Hover over Set priority → Select High.
5. Set Affinity (P-Cores): Right-click the .exe file again → Click Set affinity.
6. Uncheck All Processors, then check ONLY CPU 0, CPU 1, CPU 2, and CPU 3 (these are the
fast Performance Cores on your i7-1255U). Click OK.
Step 4: Resume and Run
1. Go back to your C++ console window.
2. Press Enter.
Your program will now unleash its full calculations, trapped exclusively on your fastest P-cores
with maximum system priority.
Keep in mind that Windows resets these Task Manager settings every time a program closes. If
you plan to test your code frequently, would you like to see how to switch Visual Studio from
Debug mode to Release mode? Release mode applies massive compiler optimizations that can
make C++ code run up to 10x faster out of the box!
Me:
You meant that solution no 3 "Automatically Boot..." Overrides solution no2 "Configure windows
for..." isn't it?
Google:
Actually, no—Solution 3 does not override Solution 2.
They handle two completely different aspects of how Windows manages your CPU and using them
together gives you the absolute maximum performance.
Here is the difference and why they work as a team:
The Analogy: A Busy Highway
Think of your CPU as a busy highway, your C++ program as an emergency vehicle, and the
Windows OS as the traffic police.
-
Solution 3 (The Code Snippet) turns on the siren. By setting your program to
HIGH\_PRIORITY\_CLASS, you tell Windows that this specific vehicle has emergency
status. It forces other normal desktop apps (like your web browser, Spotify, or background
updater) to yield and give your C++ program immediate access to the CPU lanes.
-
Solution 2 (Background Services Setting) changes the speed limit rules. Normally, Windows
is optimized for "Programs" (Foreground apps). This means Windows gives every app a very
short amount of time on the CPU before interrupting it to see if you clicked the mouse or
moved a window. By switching to Background Services, you change the system rules so that
once a heavy computational task gets a turn on the CPU, Windows lets it run for a much longer,
uninterrupted block of time before switching tasks.
How they work together
* If you only use Solution 3: Your program gets priority, but Windows will still frequently interrupt
it to keep your desktop interface feeling snappy.
* If you use both Solution 2 and Solution 3: Your C++ program jumps to the front of the line
(Priority), and once it starts calculating, Windows steps back and lets it run at full speed for longer
stretches without interrupting it (Background scheduling).
For a dedicated engineering or calculation machine, keeping both enabled is the best approach!
Are you planning to run this C++ code as a console application that you watch finish, or will it run
for hours in the background while you do other tasks?
Me:
In proposed solution "Automatically Boot.." you said: "Instead of manually using Task Manager
every time "how is this?
Google:
Using the SetPriorityClass function inside your C++ code interacts directly with the Windows
Operating System kernel.
When your program boots up, that line of code executes instantly and sends a direct request to the
Windows Scheduler. It essentially tells Windows: "Hey, I am not a normal background program.
Move me to the front of the line."
Here is exactly how that replaces the manual Task Manager steps:
How it Automates the Task Manager
Normally, to give a program maximum performance, you have to wait for it to start, open Task
Manager, find the .exe, right-click it, and manually change the priority from "Normal" to "High".
With that code snippet included:
-
Zero manual steps: Every single time you press Start/Run inside Visual Studio 2022, the
program configures itself.
-
Instant execution: It changes its own priority within microseconds of launching, meaning it
gets maximum CPU focus from the very first calculation.
-
Applies outside Visual Studio: If you build your project and send the compiled .exe file to
another Windows 11 machine, it will still automatically launch in High Priority mode on that
machine without needing Task Manager.
How to use it in your code
Just place it at the absolute top of your main function like this:
#include <iostream>
#include <windows.h> // 1. You must include this header for Windows settings
int main() {
// 2. This line replaces the manual Task Manager "Set Priority -> High" step
SetPriorityClass(GetCurrentProcess(), HIGH\_PRIORITY\_CLASS);
// 3. Your computational code goes right below it:
for (int i = 0; i < 1000000; i++) {
// Heavy calculations here...
}
std::cout << "Computation complete!" << std::endl;
return 0;
}
What if you also want to automate the "CPU Affinity" (P-Cores vs E-Cores)?
If you want your C++ program to also automatically restrict itself to your fast Performance Cores
(like we did with MATLAB) so it never touches the slow E-cores, you can add one more automated
line right below it using SetProcessAffinityMask:
// This forces the program onto CPU 0, 1, 2, and 3 (the P-Cores of your i7-1255U)// 0x0F is binary
00001111, representing the first 4 CPU threads
SetProcessAffinityMask(GetCurrentProcess(), 0x0F);
Are you working with a single-threaded application (running on one core) or a multi-threaded
application (using std::thread or OpenMP)? If you tell me, I can help you decide if restricting the
cores using affinity is a good idea for your specific C++ code.
Me:
You've just mentioned: "Using the SetPriorityClass function inside your C++ code interacts
directly with the Windows Operating System kernel. When your program boots up, that line of
code executes instantly and sends a direct request to the Windows Scheduler. It essentially tells
Windows: "Hey, I am not a normal background program. Move me to the front of the line."" but
previously you had said in Configure Windows for Background/Computational Priority: "Under
Adjust for best performance of: change the selection from Programs to Background services." how
background program is of less priority and we changed the best performance of from programs to
Background services? I am confused about Background modifier used both here and there!
Google:
It is completely normal to be confused by this! Microsoft uses the word "Background" to mean
two entirely different things in these two menus, which is incredibly misleading.
Let’s clear up the confusion by breaking down what Windows actually means in each context.
1. The Windows System Setting: "Background Services" (Quantum Length)
When you go to System Properties and change the setting from Programs to Background Services,
you are not changing the priority of apps. Instead, you are changing how long a program is allowed
to hold onto the CPU once it gets a turn.
* "Programs" mode (Default): Optimized for games and web browsers. Windows gives the active
window short, frequent bursts of CPU time (called small "quanta"). This makes the mouse cursor
feel smooth and moving windows snappy, but it forces heavy math scripts to constantly pause and
restart.
* "Background Services" mode: Optimized for databases and heavy computations. Windows tells
the CPU: "Once a program starts doing heavy work, give it a long, massive block of uninterrupted
CPU time before pausing it."
Even though it is called "Background Services," it applies to any heavy computational work you
are actively running. It stops Windows from constantly interrupting your C++ math code to update
the desktop interface.
2. The C++ Code: HIGH\_PRIORITY\_CLASS (Queue Position)
When you use SetPriorityClass in your C++ code, you are changing the program's position in line
to use the CPU.
* Every program running on your computer sits in a waiting line.
* By default, Windows treats your custom C++ program like a normal "Program” meaning it has
to wait its turn in line behind Windows Update, background telemetry, or Discord.
* When your code executes HIGH\_PRIORITY\_CLASS, it instantly jumps to the front of the
waiting line.
Putting It Together (Why They Don't Conflict)
When you combine both settings, here is what happens:
1. Thanks to your C++ Code, your program jumps straight to the front of the line (High Priority).
The CPU starts processing it immediately.
2. Thanks to the Windows Setting, once your program gets to the front of the line, the CPU doesn't
interrupt it every few milliseconds. It lets your program run for a much longer, continuous block
of time (Background Services Mode).
They work in perfect harmony: one gets you to the front of the line faster, and the other lets you
stay on the CPU longer once you get there.
Does seeing it as "Position in Line" (Priority) versus "Time Allowed on the CPU" (Windows
Setting) help clear up the terminology? If you'd like, we can look at how to ensure your Visual
Studio compiler settings are explicitly set to Release Mode to get the absolute maximum math
performance out of your C++ code next.
Me:
I would like to know how to verify if the C++ code successfully locked itself to those P-cores
while it's running, or do you want to look into compiler optimization flags (like /O2 or /Ot) to
make the math operations themselves run faster?
Google:
Let’s do both! First, I will show you how to visually verify that your code successfully locked itself
to the P-cores. Then, we will look at the crucial compiler flags to make the math itself run
exponentially faster.
Part 1: How to Verify the P-Core Lock (Affinity \& Priority)
You can use the Windows Performance Monitor or Task Manager while your C++ script is running
to prove it is locked to Cores 0–3.
Step 1: Add a Long Loop to Your Code
To give yourself time to look at the charts, make sure your code runs a loop that takes at least 10–
20 seconds (or keep the std::cin.get(); trick right after the affinity lines so you can check the settings
before the math starts).
#include <iostream>
#include <windows.h>
int main() {
// Lock to High Priority and Cores 0-3 (P-Cores)
SetPriorityClass(GetCurrentProcess(), HIGH\_PRIORITY\_CLASS);
SetProcessAffinityMask(GetCurrentProcess(), 0x0F);
std::cout << "Settings applied. Math starting now..." << std::endl;
// A massive dummy loop to max out the CPU for a few seconds
double dummy = 0.0;
for (long long i = 0; i < 5000000000LL; i++) {
dummy += 1.0;
}
std::cout << "Done! " << dummy << std::endl;
return 0;
}
Some Big Remark:
The code fragment:
for (long long i = 0; i < 5000000000LL; i++)
is valid C++ syntax, but there are important performance and correctness considerations you
should be aware of:
1. Why long long is needed
• 5000000000 exceeds the range of a 32-bit int (max ≈ 2.1 billion).
• The LL suffix makes it a long long literal (at least 64-bit), so it fits.
• Without LL, this would cause a compiler warning or overflow.
2. Performance concerns
• This loop will run 5 billion iterations.
• Even at 1 nanosecond per iteration (which is unrealistically fast), it would take ~5 seconds;
in reality, it could take tens of seconds or minutes depending on the work inside.
• Such a large loop can be CPU-intensive and may not be practical unless you truly need that
many iterations.
Step 2: Watch the CPU Cores Light Up
1. Launch your program from Visual Studio.
2. Open Task Manager (Ctrl + Shift + Esc) and go to the Performance tab (the graph icon).
3. Click on CPU, right-click the big graph, and select Change graph to -> Logical processors.
4. Look at the 12 grids (your i7-1255U has 12 logical threads).
5. Proof: You will see CPU 0, 1, 2, and 3 spike to 100% utilization, while CPU 4 through 11 sit
completely idle. If you right-click your process in the Details tab and check "Set affinity", you will
see the boxes for Cores 0–3 are already checked automatically!
Part 2: Compiler Optimization Flags (The Real Speed Boost)
By default, Visual Studio compiles in Debug mode, which turns off all optimizations so you can
read line-by-line errors. For mathematical computations, running in Debug mode is like driving a
supercar in first gear.
To unleash the math engine, we need to switch to Release Mode and check two specific flags:
1. Switch to Release Mode (Easiest 10x Speedup)
At the very top toolbar of Visual Studio, look next to the green "Play" button. Change the dropdown
menu from Debug to Release. This instantly activates basic math optimizations.
2. Fine-Tune the Flags (/O2 vs /Ot)
Right-click your Project in the Solution Explorer → Properties → C/C++ → Optimization:
* Optimization: Maximize Speed (/O2) — Recommended. This tells the compiler to rewrite your
math equations behind the scenes into the most efficient machine code possible. It optimizes for
raw execution speed.
* Favor Size or Speed: Favor Fast Code (/Ot) — This explicitly instructs the compiler to prioritize
execution speed over the final file size of your .exe.
3. Enable SIMD Vectorization (/arch:AVX2)
Your i7-1255U has advanced mathematical hardware extensions (AVX2) that allow it to calculate
multiple math operations simultaneously in a single CPU cycle (Vectorization). R2014a MATLAB
couldn't use this, but your C++ code can!
1. In the Project Properties window, go to C/C++ → Code Generation.
2. Find Enable Enhanced Instruction Set.
3. Change it to Advanced Vector Extensions 2 (/arch:AVX2).
Would you like me to show you how to write a quick high-resolution timer in your C++ code so
you can measure down to the microsecond exactly how many seconds these compiler changes
shave off your execution time?
Me:
I think the profiler is enough, isn't it?
Google:
Yes, you are absolutely right! The Visual Studio Performance Profiler is a phenomenal tool. It is
much more powerful than a simple timer because it doesn't just tell you how long the code took—
it shows you exactly which lines of code are slowing you down.
Since you are running heavy mathematical computations on a hybrid processor (i7-1255U), using
the built-in Profiler is the smartest way to verify your optimizations.
Here is what you should look for in the Profiler to confirm your P-Core lock and compiler flags
are working:
1. How to check CPU Usage in the Profiler:
1. In Visual Studio, go to the top menu and select Debug → Performance Profiler...
(or press Alt + F2).
2. Check the box for CPU Usage and click Start.
3. Let your mathematical script run to completion.
2. What a "Healthy" Math Profile looks like
When you analyze the report, look for these three indicators to prove your machine is running at
peak compatibility and speed:
• The "Total CPU" Graph Caps at \~33%: Because your i7-1255U has 12 logical threads, and
your P-Core affinity mask (0x0F) limits the program to the first 4 threads, a single-threaded
or lightly multi-threaded math loop will max out those specific cores. The total CPU graph
will show a flat, stable line at around 25% to 33% total capacity. If it spikes to 100%, it
means the affinity mask didn't hold and it bled into your slow E-cores.
• Look at the Flame Graph (Hot Path): The profiler will show you the "Hot Path"—the exact
function or math loop consuming 99% of your time.
• Debug vs. Release Profile: If you profile in Debug mode, you will see a lot of hidden
overhead operations (like iterator validations and memory tracking). If you switch to
Release mode with /O2 and /arch:AVX2 enabled, you will notice those overhead steps
completely disappear, leaving only raw, vectorized assembly instructions.
Would you like help analyzing the Profiler's Hot Path output to see if any specific math operations
(like vector allocations or matrix loops) can be written differently to better utilize your CPU cache?
Me:
Thank you, can you give me a good reference to refer ack to when facing such obstacles.
Google:
You are very welcome! When dealing with hardware-software mismatch, performance tuning, and
Windows scheduling, having trusted resources saves hours of troubleshooting.
Here are the best, industry-standard references to keep in your bookmarks for these specific
obstacles:
1. Modern CPU Architecture \& Core Optimization
• Intel Architecture Optimization Reference Manual: This is the holy grail straight from Intel.
Search for their chapters on "Hybrid Architecture" and "Intel Thread Director." It explains
exactly how Windows 11 splits workloads between P-cores and E-cores, and provides deep
coding techniques for developers to maximize throughput on processors like your Core i7.
• Agner Fog’s Software Optimization Resources: A legendary resource in the computer
engineering world. His downloadable guides on optimizing C++ assembly, loops, and
vector operations are unparalleled for making raw math code run as fast as humanly
possible.
2. Windows Kernel & Thread Scheduling
• Windows Internals (Book by Pavel Yosifovich, Mark Russinovich, et al.): The absolute
definitive guide on how Windows manages memory, processes, priorities, and threads.
Chapter 3 (Processes and Threads) covers exactly how the Windows Scheduler decides
which application gets CPU time and how setting priority/affinity alters that behavior.
• Microsoft Learn (System Services API Documentation): Bookmark the documentation pages
for SetPriorityClass, SetProcessAffinityMask, and Multimedia Class Scheduler Service
(MMCSS). Microsoft explicitly details the technical boundaries of thread priorities and
process quanta limits here.
3. Visual Studio Tuning & Compiler Flags
• Microsoft
Learn - MSVC Compiler Options: Keep the reference pages for MSVC
Optimization Flags bookmarked. It lists every single command-line switch (like /O2, /Ot,
and /arch:AVX2), detailing exactly what structural changes the compiler makes to your
loops and arrays behind the scenes.
4. MATLAB Specific Performance \& Compatibility
• MathWorks Support - System Requirements \& Platform Roadmap: MathWorks updates this
page for every new release. It is the best place to check which versions of Windows are
natively compatible with which versions of MATLAB, preventing you from installing
outdated releases on newer operating systems.
Would you like me to help you find the direct download links to any of these manuals, or do you
have any final questions about benchmarking your current C++ code before you dive in?
Me:
Let's get into the links please.
Google:
1. Modern CPU Architecture & Core Optimization:
• Intel Developer Hub: Access the latest version of the core guides through the Intel 64 and
-
IA-32 Architectures Software Developer Manuals hub:
https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html
• Direct Manual: Open the Intel 64 and IA-32 Architectures Optimization Reference Manual
-
(Volume 1) for code-level optimization on modern CPU architectures:
https://www.intel.com/content/www/us/en/content-details/671488/intel-64-and-ia-32architectures-optimization-reference-manual-volume-1.html
• Agner Fog’s Guides:
-
https://www.agner.org/optimize/
2. Windows Kernel & Thread Scheduling
• Windows Architecture Guide: Read the breakdown of the kernel structure via the official:
-
https://learn.microsoft.com/en-us/sysinternals/resources/windows-internals
• Priority API: Review parameters and edge cases on the:
- https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nfprocessthreadsapi-setpriorityclass
• Scheduling Mechanics: Learn how Windows handles tasks under the hood using the:
- https://learn.microsoft.com/en-us/windows/win32/procthread/scheduling-priorities
3. Visual Studio Tuning & Compiler Flags
• Optimization Options: Check the full list of speed switches on the:
-
https://learn.microsoft.com/en-us/cpp/build/reference/o-options-optimize-code?view=msvc170
• MSVC Options Index: View every available flag category using the comprehensive:
- https://learn.microsoft.com/en-us/cpp/build/reference/compiler-options?view=msvc-170
Let me know if you would like me to write a quick C++ example demonstrating SIMD
vectorization (AVX2) so you can see how it forces the i7-1255U to crunch multiple math data
points at the exact same time!
Me:
Ok
Google:
Here is the exact C++ example demonstrating how to leverage the SIMD (Single Instruction,
Multiple Data) hardware via the AVX2 instruction set built directly into your Core i7-1255U.
Instead of processing values one by one, this tells the CPU to process 4 double-precision floats or
8 integers at the exact same time in a single clock cycle, dramatically speeding up mathematical
loops.
C++ Code for Manual AVX2 Vectorization
\#include <iostream>
#include <immintrin.h> // 1. Required header for AVX intrinsic functions
#include <windows.h>
int main() {
// Apply the Priority and P-Core Affinity optimizations we set up earlier
SetPriorityClass(GetCurrentProcess(), HIGH\_PRIORITY\_CLASS);
SetProcessAffinityMask(GetCurrentProcess(), 0x0F);
// 2. Prepare data aligned to 32-byte boundaries (required for 256-bit AVX registers)
alignas(32) double arrayA[4] = { 1.0, 2.0, 3.0, 4.0 };
alignas(32) double arrayB[4] = { 10.0, 20.0, 30.0, 40.0 };
alignas(32) double result[4] = { 0.0, 0.0, 0.0, 0.0 };
// 3. Load the data from normal RAM into the dedicated 256-bit CPU registers
__m256d va = _mm256_load_pd(arrayA);
__m256d vb = _mm256_load_pd(arrayB);
// 4. THE MAGIC: The CPU adds all 4 numbers together simultaneously in a single cycle!
__m256d vresult = _mm256_add_pd(va, vb);
//5. Store the vector register result back into standard RAM array
_mm256_store_pd(result, vresult);
// Print results to confirm calculation
std::cout << "Vectorized calculation result: " << std::endl;
for (int i = 0; i < 4; i++) {
std::cout << result\[i] << " ";
// Outputs: 11, 22, 33, 44
}
std::cout << std::endl;
return 0;
}
How the Visual Studio Profiler Sees This
When you run the Performance Profiler in Release Mode with the /arch:AVX2 flag checked in
your project settings:
1. The compiler will scan your code and automatically convert standard calculations into these
vector instructions (a process called Auto-Vectorization).
2. Inside the profiler report, you will see a massive drop in total CPU cycle overhead for math
operations because the hardware is crunching data blocks in parallel rather than cycling through
them one at a time.
Would you like to know how to structure your standard for loops so that the Visual Studio
compiler automatically converts them into AVX2 instructions without you having to write these
complex \_mm256\_... functions manually?
Me:
yes!
Google:
To get the Visual Studio compiler to automatically convert your normal for loops into vectorized
AVX2 code (a process called Auto-Vectorization), you don't need to write complex intrinsic
functions. You just need to follow a few strict coding rules that allow the compiler's optimizer to
do the heavy lifting safely.
Here is the template for a perfectly vectorizable loop and the rules to make it work:
The Auto-Vectorization Code Template
#include <iostream>
#include <vector>
#include <windows.h>
// Using a constant size helps the compiler optimize loop boundsconst int SIZE = 1000000;
int main() {
SetPriorityClass(GetCurrentProcess(), HIGH\_PRIORITY\_CLASS);
SetProcessAffinityMask(GetCurrentProcess(), 0x0F);
// 1. Contiguous memory allocation (std::vector or raw arrays work perfectly)
std::vector<double> A(SIZE, 1.5);
std::vector<double> B(SIZE, 2.5);
std::vector<double> C(SIZE, 0.0);
// 2. The Loop: Clean, independent, and predictable
// Make sure your Project Properties -> C/C++ -> Code Generation -> Enable Enhanced Instruction Set is set to AVX2 (AVX2)
for (int i = 0; i < SIZE; ++i) {
C[i] = A[i] * B[i] + 5.0; // The compiler will process 4 of these multiplications at once!
}
std::cout << "Calculation complete. Index 0: " << C\[0] << std::endl;
return 0;
}
The 4 Golden Rules for Auto-Vectorization
If your loop violates any of these rules, the Visual Studio compiler will panic, disable vectorization,
and fall back to slow, single-item processing.
1. No Data Dependencies (Crucial)
Each iteration of the loop must be completely independent of the previous one.
Bad (Cannot Vectorize): C[i] = C[i-1] + A[i]; (The CPU must wait for step i-1 to finish before
calculating step i).
Good: C[i] = A[i] + B[i]; (The CPU can calculate indexes 0, 1, 2, and 3 all at the exact same
moment).
2. Avoid Branching (if statements) Inside the Loop
Conditional jumps break the pipeline of vector hardware.
Bad: Putting an if (A[i] > 10) { ... } else { ... } inside your loop.
Good: Keep the math uniform for every element in the array. If you absolutely need conditional
logic, look up ternary operators (C[i] = (A[i] > 10) ? X : Y;), which MSVC can sometimes vectorize
using hardware masks.
3. Continuous Memory Layout
The data must sit right next to each other in your RAM so the CPU can grab a massive block of it
at once.
Good: std::vector, std::array, or standard arrays (like double A\[1000]).
Bad: std::list or arrays of pointers to objects. Because pointer data is scattered all over your
RAM, the CPU cannot load it into a vector register simultaneously.
4. Clean Counter and Bounds
The loop must have a clear start, a clear end, and a straight step counter.
Good: for (int i = 0; i < SIZE; ++i)
Bad: Modifying the loop counter inside the loop body (e.g., adding i++ inside the math block)
or using a loop termination condition that changes dynamically.
How to prove the compiler successfully vectorized it
You don't even have to guess! You can ask Visual Studio to tell you exactly which loops it
successfully vectorized and which ones failed:
1. Right-click your project $\\rightarrow$ Properties $\\rightarrow$ C/C++ $\\rightarrow$
Command Line.
2. In the Additional Options box at the bottom, type: /Qvec-report:2
3. Click Apply and OK.
4. When you compile your project in Release mode, look at the Output Window. The compiler will
print explicit messages like:
* compiler message: loop vectorized
* compiler message: loop not vectorized (reason code: 1200) (If it fails, it gives you a code
explaining exactly which rule you broke!).
Would you like me to look at one of your actual mathematical loops to check if it matches these
rules, or are you ready to test Qvec-report:2 on your project?
Me:
Let's do it another time. Thanks.
Me:
Configure Windows for Background/Computational Priority:: I think this solution for boosting
performance of Visual Studio C++ IDE 2022 on windows11 Pro is Very Risky. how to make this
possible only for certain application "the visual studio only" to ensure no virus will take advantage
of this capability?
Google:
The Windows NT kernel does not support per-application quantum (timing) adjustments. The
time-slice length—whether the CPU gives short, snappy quantums or long, continuous blocks—is
a global scheduler rule controlled entirely by the system-wide Win32PrioritySeparation setting.
You cannot tell Windows to give a long quantum to Visual Studio while keeping short quantums
for everything else.
However, you can achieve the exact same functional result (keeping Visual Studio running
continuously without being interrupted by background noise) for just that single program by
combining two native features:
1. Core Isolation (The Ultimate Bypass)
When you assign Visual Studio to specific physical P-cores using CPU affinity (as discussed
previously), you remove the need to change global Windows timing altogether.
• By dedicating, say, Cores 0 through 7 exclusively to Visual Studio and moving all background
Windows tasks, browsers, and Discord to the remaining E-cores, Windows has no choice
but to let Visual Studio run uninterrupted on its designated cores.
• Because those cores have zero background thread congestion, Visual Studio effectively
enjoys an uninterrupted, continuous "long quantum" experience without altering systemwide security boundaries.
2. Fine-Tuning Thread Priorities via Process Hacker
If you want to push a single program further than standard Windows Task Manager allows without
touching global settings, you can use an advanced tool like Process Hacker (or Process Explorer):
Launch Visual Studio.
1.Open Process Hacker, find devenv.exe, right-click it, go to Priority, and set it to High.
2.Expand devenv.exe to view its individual worker threads (like MSBuild or compiler threads).
You can selectively right-click specific heavy compilation threads and raise their individual
thread priorities to Above Normal or Highest, leaving the UI threads at normal. This
ensures compilation threads hog the CPU time slices on your P-cores while keeping the
interface responsive.
Me:
You are sure that affinity means dedicating certain cores to the VS IDE only, and no other running
programs (MS word, internet explorer, or adobe reader etc.) will use these cores while the IDE is
running my source code?
Google:
No, that is a common misconception. Setting CPU affinity does not create an exclusive
reservation that locks other programs out of those cores.
CPU affinity is a one-way restriction placed only on the target application:
• When you set affinity for Visual Studio to use specific cores (like your P-cores), you are
telling Windows: "Visual Studio is only allowed to run on these cores."
• You are not telling Windows: "Block MS Word, background services, Chrome, or other apps
from using these cores."
By default, Windows will still schedule background tasks, system interrupts, and other running
applications on those exact same cores whenever Visual Studio yields the CPU or finishes a task
slice. True core isolation (where specific cores are completely hidden from the rest of the operating
system) requires advanced kernel-level configuration (like processor isolation in server
environments or virtual machines), which Windows 11 Pro does not expose for standard desktop
apps.
If your primary goal is to ensure maximum safety against malware or unauthorized software
hijacking your hardware capabilities, your best defense remains standard OS security (Windows
Defender, keeping software updated) rather than trying to manually partition CPU cores, because
Windows handles core allocation dynamically for all software running on the machine.
Me:
But you have just mentioned this:
“Core Isolation (The Ultimate Bypass)
When you assign Visual Studio to specific physical P-cores using CPU affinity (as discussed
previously), you remove the need to change global Windows timing altogether.
By dedicating, say, Cores 0 through 7 exclusively to Visual Studio and moving all background
Windows tasks, browsers, and Discord to the remaining E-cores, Windows has no choice but to let
Visual Studio run uninterrupted on its designated cores.
Because those cores have zero background thread congestion, Visual Studio effectively enjoys an
uninterrupted, continuous "long quantum" experience without altering system-wide security
boundaries.”
Google:
You are completely right to call that out, and I apologize for the contradiction. My phrasing of
"exclusively" in that earlier explanation was loose and misleading.
Let me correct the record clearly: Standard CPU affinity does not block other programs from
using those cores.
When you set an affinity mask for Visual Studio to use Cores 0 through 7:
1.Visual Studio is forbidden from using any other cores.
2.Windows is still fully allowed to schedule background services, system interrupts, or other
apps (like Chrome or Word) onto those exact same cores if the scheduler deems it
necessary.
To actually achieve true exclusivity (meaning zero other apps touch Cores 0–7), you would have
to manually configure the affinity of every single other background process and Windows service
on your system to run only on the E-cores. Doing that manually for the entire operating system is
tedious, prone to breaking Windows components, and generally not recommended.
What actually happens in practice?
While Windows can still put other tasks on your P-cores, Windows 11 has a built-in hardware
scheduler called Thread Director (especially on Intel Core processors) that is designed to push
background, low-priority tasks to E-cores by default, while routing heavy computational tasks (like
compiling C++ code in Visual Studio) to the P-cores.
So while it isn't a hard cryptographic or kernel-level lock keeping other apps out, setting VS to
your P-cores combined with High Priority naturally gives it dominant access to those hardware
threads without needing to alter global system timing or compromise your system's security
boundaries.
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )