C# 如何设置程序的 CPU 亲和性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1052276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to set CPU affinity of a program?
提问by George2
I have a program written in C#, I am using VSTS 2008 + .Net 3.5 + Windows Vista Enterprise x86 to develop a Windows Forms application.
我有一个用 C# 编写的程序,我使用 VSTS 2008 + .Net 3.5 + Windows Vista Enterprise x86 来开发 Windows 窗体应用程序。
My current computer is dual-core CPU, I want to set CPU affinity of my program to run on a specific CPU and free another CPU to do some other job. Any ideas how to do this? Either through coding or configuration is ok.
我当前的计算机是双核 CPU,我想设置我的程序的 CPU 亲和性以在特定 CPU 上运行并释放另一个 CPU 来做其他工作。任何想法如何做到这一点?通过编码或配置都可以。
A little more background is, my program is CPU intensive, so I do not want to let it occupy all two CPU resources on my computer and I want to free one CPU so that I can browse network at the same time quickly. :-)
多一点背景是,我的程序是CPU密集型的,所以我不想让它占用我计算机上的所有两个CPU资源,我想释放一个CPU以便我可以同时快速浏览网络。:-)
thanks in advance, George
提前致谢,乔治
回答by Brian Rasmussen
Actually, your application will not use more than one CPU unless you specifically do something to utilize more CPUs. If you use the thread pool and/or start additional threads you may use additional available cores, but otherwise your application will just have one thread per default and thus only use one CPU.
实际上,您的应用程序不会使用多个 CPU,除非您专门做一些事情来使用更多 CPU。如果您使用线程池和/或启动额外的线程,您可能会使用额外的可用内核,否则您的应用程序每个默认只有一个线程,因此只使用一个 CPU。
回答by Gaurav
- Go to Task Manager-> Processestab.
- Look for your program. Right click on it.
- Select Set Affinityand uncheck one of the checkboxes.
- 转到任务管理器->进程选项卡。
- 寻找你的程序。右键单击它。
- 选择Set Affinity并取消选中其中一个复选框。
This should free up one processor for you.
这应该为您释放一个处理器。
For doing it from the code you can add this statement:
要从代码中执行此操作,您可以添加以下语句:
System.Diagnostics.Process.GetCurrentProcess().ProcessorAffinity = (System.IntPtr) 1;
Cheers!
干杯!
回答by mghie
The Windows API functions to do this are SetProcessAffinityMask()and SetThreadAffinityMask(). I don't know .NET so I can't say whether there are wrappers around those functions, but thisseems to suggest otherwise.
执行此操作的 Windows API 函数是SetProcessAffinityMask()和SetThreadAffinityMask()。我不知道这样的.NET我不能说是否有围绕这些函数的包装,但是这似乎并非如此。
BTW: I agree that these are necessary only in very specific circumstances, it's normally best to let the OS scheduler deal with it. It's one of those questions where you probably shouldn't do it if you have to ask how.
顺便说一句:我同意这些只有在非常特殊的情况下才是必要的,通常最好让 OS 调度程序处理它。如果您必须询问如何做,这是您可能不应该这样做的问题之一。