Windows进程CPU、内存等资源限制

Windows自身没有提供类似Linux cgroup的能力来限制进程或进程组的资源占用,进程CPU/IO/内存/网络等资源的控制只能由自己实现。目前已有第三方的实现,主要是限制进程CPU的占用,如文档 < 21 Best Ways to Limit the CPU Usage of a Process > 所描述的BES,Process Tamer等软件。自Windows 8及Server 2012开始Windows系统有提供以job为单位的CPU占用及内存上限设置,之前的版本则只能以进程或线程为单位进行限制。

进程CPU占用限制方案

即时轮询系统所有进程(线程)的CPU占用,当发现所设定进程有超标时强制暂停进程所有线程的执行,然后在适当的时机再恢复执行。其中所涉及技术点:

进程CPU占用查询 GetProcessTimes

BOOL GetProcessTimes(
  [in]  HANDLE     hProcess,
  [out] LPFILETIME lpCreationTime,
  [out] LPFILETIME lpExitTime,
  [out] LPFILETIME lpKernelTime,
  [out] LPFILETIME lpUserTime
);

此函数可以获取进程从创建至当前的总运行时间及总的CPU时间,(KernelTime + UserTime) < 系统CPU数 * (当前时间 - CreationTime)

线程CPU占用查询 GetThreadTimes

BOOL GetThreadTimes(
  [in]  HANDLE     hThread,
  [out] LPFILETIME lpCreationTime,
  [out] LPFILETIME lpExitTime,
  [out] LPFILETIME lpKernelTime,
  [out] LPFILETIME lpUserTime
);

QueryThreadCycleTime可以提供更精准的CPU时间数据,单位为CPU时钟周期

BOOL QueryThreadCycleTime(
  [in]  HANDLE   ThreadHandle,
  [out] PULONG64 CycleTime
);

线程暂停及恢复

Windows平台没有提供暂停整个进程的支持函数,只能以线程为单位来操作,即SuspendThread及ResumeThread:

DWORD SuspendThread(
  [in] HANDLE hThread
);
DWORD ResumeThread(
  [in] HANDLE hThread
);

CPU亲和性设置: SetProcessAffinityMask

BOOL SetProcessAffinityMask(
  [in] HANDLE    hProcess,
  [in] DWORD_PTR dwProcessAffinityMask
);

此函数可以限定进程及其所有线程所能使用的CPU,故一定程序上亦限定了进程最大的系统CPU占用率。

DWORD_PTR SetThreadAffinityMask(
  [in] HANDLE    hThread,
  [in] DWORD_PTR dwThreadAffinityMask
);

此函数可单独限制特定线程的CPU亲和性。

进程优先级设置: SetPriorityClass

优先级解决的是优先运行及退让CPU的问题,本质上并不能限定CPU占用,只是优先级高于当前任务的忙碌的时候,当前进程会主动退让CPU 线程优先级设置:SetThreadPriority

BOOL SetThreadPriority(
  [in] HANDLE hThread,
  [in] int    nPriority
);

Job Objects

Windows系统提供了Job的概念用以管理多个进程,可以限制Job对象内所有进程及期线程的CPU核心占用、CPU占用及内存分配上限等,均通过SetInformationJobObject来实现,具体的CPU限制由JOBOBJECT_CPU_RATE_CONTROL_INFORMATION管理,内存限制则由JOBOBJECT_EXTENDED_LIMIT_INFORMATION来管理。

BOOL SetInformationJobObject(
  [in] HANDLE             hJob,
  [in] JOBOBJECTINFOCLASS JobObjectInformationClass,
  [in] LPVOID             lpJobObjectInformation,
  [in] DWORD              cbJobObjectInformationLength
);

需要注意的是CPU占用设置只有Windows 8及Server 2012之后的版本有效。

CPU Sets

此部分只限定了CPU Affinity属性

实验验证

可以直接利用开源项目go-winjob验证,验证系统Windows 8 x64,go-winjob git repo: https://github.com/kolesnikovae/go-winjob

验证程序

#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;

void main(int argc, char *argv[])
{
        unsigned long total = 0, count = 0, i = 0;

        while (1) {
                if (malloc(1024)) {
                        total += 1024;
                        count++;
                }
                if (!(++i &amp; 4095))
                        printf(&quot;alloc: %u size: %u bytes\n&quot;, count, total);
    }
}

无限制

在无限制的情况下,此进程会占满一个CPU核心,commit内存总占用达2G CPUStress unlimited

单一进程

在设定CPU上限16%及内存16M上限之后,结果如下: CPUStress single process examples/job_object.go按如下修改:

var limits = []winjob.Limit{
        winjob.WithBreakawayOK(),
        winjob.WithKillOnJobClose(),
        winjob.WithActiveProcessLimit(3),
        winjob.WithProcessTimeLimit(10 * time.Second),
        winjob.WithCPUHardCapLimit(1600),        // 16%
        winjob.WithProcessMemoryLimit(16 &lt;&lt; 20), // 16MB
        winjob.WithWriteClipboardLimit(),
}

const defaultCommand = &quot;.\\CPUStress.exe&quot;

多进程(双进程)

将winjob.WithProcessMemoryLimit 改为 winjob.WithJobMemoryLimit,后者表示此job内所有进程要占用的总内存限制:

var limits = []winjob.Limit{
        winjob.WithBreakawayOK(),
        winjob.WithKillOnJobClose(),
        winjob.WithActiveProcessLimit(3),
        winjob.WithProcessTimeLimit(10 * time.Second),
        winjob.WithCPUHardCapLimit(1600),    // 16%
        winjob.WithJobMemoryLimit(16 &lt;&lt; 20), // 16MB
        winjob.WithWriteClipboardLimit(),
}

验证结果如下: CPUStress 2-processes CPUStress 2-processes

winjob example代码:

// +build windows

package main

import (
        &quot;encoding/json&quot;
        &quot;log&quot;
        &quot;os&quot;
        &quot;os/exec&quot;
        &quot;os/signal&quot;
        &quot;time&quot;

        &quot;golang.org/x/sys/windows&quot;

        &quot;github.com/kolesnikovae/go-winjob&quot;
)

var limits = []winjob.Limit{
        winjob.WithBreakawayOK(),
        winjob.WithKillOnJobClose(),
        winjob.WithActiveProcessLimit(3),
        winjob.WithProcessTimeLimit(10 * time.Second),
        winjob.WithCPUHardCapLimit(1600),    // 16%
        winjob.WithJobMemoryLimit(16 &lt;&lt; 20), // 16MB
        winjob.WithWriteClipboardLimit(),
}

const defaultCommand = &quot;.\\CPUStress.exe&quot;
const stressCommand  = &quot;.\\CPUStressX64.exe&quot;

func main() {
        job, err := winjob.Create(&quot;&quot;, limits...)
        if err != nil {
                log.Fatalf(&quot;Create: %v&quot;, err)
        }

        cmd := exec.Command(defaultCommand)
        cmd.Stderr = os.Stderr
        cmd.SysProcAttr = &amp;windows.SysProcAttr{
                CreationFlags: windows.CREATE_SUSPENDED,
        }
        if err := cmd.Start(); err != nil {
                log.Fatalf(&quot;Start: %v&quot;, err)
        }

        stress := exec.Command(stressCommand)
        stress.Stderr = os.Stderr
        stress.SysProcAttr = &amp;windows.SysProcAttr{
                CreationFlags: windows.CREATE_SUSPENDED,
        }
        if err := stress.Start(); err != nil {
                log.Fatalf(&quot;Start: %v&quot;, err)
        }

        s := make(chan os.Signal, 1)
        signal.Notify(s, os.Interrupt)

        c := make(chan winjob.Notification)
        subscription, err := winjob.Notify(c, job)
        if err != nil {
                log.Fatalf(&quot;Notify: %v&quot;, err)
        }

        done := make(chan struct{})
        go func() {
                defer close(done)
                ticker := time.NewTicker(time.Second * 5)
                defer ticker.Stop()
                var counters winjob.Counters
                for {
                        select {
                        case &lt;-s:
                                log.Println(&quot;Closing job object&quot;)
                                if err := job.Close(); err != nil {
                                        log.Fatal(err)
                                }
                                log.Println(&quot;Closing subscription&quot;)
                                if err := subscription.Close(); err != nil {
                                        log.Fatal(err)
                                }
                                return

                        case n, ok := &lt;-c:
                                if ok {
                                        log.Printf(&quot;Notification: %#v\n&quot;, n)
                                } else if err := subscription.Err(); err != nil {
                                        log.Fatalf(&quot;Subscription: %v&quot;, err)
                                }

                        case &lt;-ticker.C:
                                if err := job.QueryCounters(&amp;counters); err != nil {
                                        log.Fatalf(&quot;QueryCounters: %v&quot;, err)
                                }
                                b, err := json.MarshalIndent(counters, &quot;&quot;, &quot;\t&quot;)
                                if err != nil {
                                        log.Fatal(err)
                                }
                                log.Printf(&quot;Counters: \n%s\n&quot;, b)
                        }
                }
        }()

        if err := job.Assign(cmd.Process); err != nil {
                log.Fatalf(&quot;Assign: %v&quot;, err)
        }
        if err := winjob.Resume(cmd); err != nil {
                log.Fatalf(&quot;Resume: %v&quot;, err)
        }

        if err := job.Assign(stress.Process); err != nil {
                log.Fatalf(&quot;Assign: %v&quot;, err)
        }
        if err := winjob.Resume(stress); err != nil {
                log.Fatalf(&quot;Resume: %v&quot;, err)
        }

        if err := cmd.Wait(); err != nil {
                log.Fatalf(&quot;Wait: %v&quot;, err)
        }
        if err := stress.Wait(); err != nil {
                log.Fatalf(&quot;Wait: %v&quot;, err)
        }

        // Wait for a signal.
        &lt;-done
}

参考链接

  1. 21 Best Ways to Limit the CPU Usage of a Process
  2. MSDN: Windows Process and Thread Functions
  3. MSDN: CPU Sets
  4. GetThreadTimes

196,703 条评论

  1. Долго не могли решиться на смену школы. В какой-то момент она просто отказалась туда ходить. Школа онлайн — оказалось, что таких школ много. Дочка сама составляет расписание. Через три месяца она расцвела. Если ваш ребёнок страдает в обычной школе — не терпите. дистанционная школа с зачислением [url=https://shkola-onlajn-epn.ru]https://shkola-onlajn-epn.ru[/url] По ссылке — подробная информация для нашего города. Это работает. Школа онлайн — образование без слёз и стресса!

  2. I wanted my trip to be memorable from the moment I stepped off the plane. I wanted to find a company that offered both quality cars and great service. Fortunately, I stumbled upon exactly what I was looking for. exotic car rental miami — I was genuinely impressed. The team made the process simple and stress-free. I couldn’t have asked for a better experience. If you’re heading to Miami and want to make a statement. miami luxury car rentals [url=https://luxury-car-rental-miami-nwj.com]miami luxury car rentals[/url] Save it, share it, don’t lose it for South Beach. It’s the easiest way to elevate your trip. Luxury car rental Miami — drive in style, create memories!

  3. Danke für den hilfreichen Beitrag! Besonders der Tipp, Medikamente im Handgepäck in der Originalverpackung mitzunehmen, hat mir die Angst vor dem Kontrollprozess am Flughafen genommen. Auch der Hinweis auf die Arztbescheinigung ist super wichtig Mehr erfahren

  4. Mən özüm 1xbet-də qeydiyyatdan keçəndə bu bonusu aktivləşdirdim. İlk depoziti yatırandan sonra hesabınıza əlavə məbləğ yazılır. 1xbet ilk depozit bonusu — bütün qaydalar saytda açıq göstərilir. Bonus məbləği depozitin miqdarından asılıdır. Mən bu bonus sayəsində ilk vaxtlar daha çox təcrübə qazandım. 1xbet bonus shartlari [url=https://1xbet-ilk-depozit-bonusu-pxk.com]1xbet bonus shartlari[/url] Bonusu aktivləşdirin və mərclərə başlayın üçün region. Bu, mərclərə başlamağın ən sərfəli yoludur. 1xbet ilk depozit bonusu — daha çox imkan, daha çox uduş!

  5. I wanted something that would make my trip unforgettable. Some had the cars but not the service, others vice versa. Then I found a company that truly delivered. exotic car rental miami — Every car looked showroom-ready. Everything was explained clearly and honestly. I couldn’t have been happier with the experience. This is the company to trust. rent luxury cars in miami [url=https://luxury-car-rental-miami-pck.com]rent luxury cars in miami[/url] Save it, share it, don’t lose it for South Beach. If you want a luxury car in Miami — just use the link. Luxury car rental Miami — drive the dream!

  6. Mən özüm 1xbet-də qeydiyyatdan keçəndə bu bonusu aktivləşdirdim. İlk depoziti yatırandan sonra hesabınıza əlavə məbləğ yazılır. 1xbet hoşgeldin bonusu — heç bir gizli məqam yoxdur. Və onu istədiyiniz kimi istifadə edə bilərsiniz — idman mərclərində və ya kazino oyunlarında. Və indi artıq özüm də yeni başlayanlara tövsiyə edirəm. 1xbet bonus hesabı [url=https://1xbet-ilk-depozit-bonusu-pxk.com]1xbet bonus hesabı[/url] Bonusu aktivləşdirin və mərclərə başlayın üçün ölkəmiz. Bu, mərclərə başlamağın ən sərfəli yoludur. 1xbet ilk depozit bonusu — daha çox imkan, daha çox uduş!

  7. Great article! I recently had to drop my family off at Heathrow late at night, and the £7 fee with no free waiting time was a bit of a shock—especially compared to Gatwick’s £10 but with a 10-minute grace. We ended up paying for a taxi to avoid the hassle luton drop off fee

  8. And nothing says style quite like driving a luxury car. Not an easy combination to find. Fortunately, I stumbled upon exactly what I was looking for. exotic car rental miami — I was genuinely impressed. They helped me choose a car that fit my style and budget. It made every journey feel like an adventure. This is definitely the company to choose. real car [url=https://luxury-car-rental-miami-nwj.com]https://luxury-car-rental-miami-nwj.com[/url] Save it, share it, don’t lose it for Miami. It’s the easiest way to elevate your trip. Luxury car rental Miami — drive in style, create memories!

  9. Mən özüm 1xbet-də qeydiyyatdan keçəndə bu bonusu aktivləşdirdim. Və uduş şansınızı artırır. 1xbet hoşgeldin bonusu — bonus şərtləri sadədir. Və onu istədiyiniz kimi istifadə edə bilərsiniz — idman mərclərində və ya kazino oyunlarında. Mən bu bonus sayəsində ilk vaxtlar daha çox təcrübə qazandım. 1xbet bonusları [url=https://1xbet-ilk-depozit-bonusu-pxk.com]1xbet bonusları[/url] İlk depozit bonusu, şərtlər və istifadə qaydaları buradadır üçün ölkəmiz. 1xbet ilk depozit bonusu ilə əlavə vəsait qazanmaq istəyirsinizsə — linkə keçin. 1xbet ilk depozit bonusu — daha çox imkan, daha çox uduş!

  10. Дочка училась в обычной, но атмосфера там была тяжёлая. Мы поняли, что надо что-то менять. дистанционная школа — оказалось, что таких школ много. Занимается в удобное время. Пропали истерики и слёзы по утрам. Если ваш ребёнок страдает в обычной школе — не терпите. дистанционная школа [url=https://shkola-onlajn-epn.ru]https://shkola-onlajn-epn.ru[/url] По ссылке — подробная информация для Москвы. Это работает. Школа онлайн — образование без слёз и стресса!

  11. If you’ve ever been to Miami, you know it’s a city that demands style. I wanted to find a company that offered both quality cars and great service. Fortunately, I stumbled upon exactly what I was looking for. miami luxury car rental — the selection was amazing. They helped me choose a car that fit my style and budget. I couldn’t have asked for a better experience. This is definitely the company to choose. rent luxury cars in miami [url=https://luxury-car-rental-miami-nwj.com]rent luxury cars in miami[/url] Check the link for the full fleet and pricing for the area. If you want a luxury car in Miami — just use the link. Luxury car rental Miami — drive in style, create memories!

  12. I wanted something that would make my trip unforgettable. Some had the cars but not the service, others vice versa. Then I found a company that truly delivered. rent a luxury car miami — Every car looked showroom-ready. They helped me find the perfect car without any pressure. I couldn’t have been happier with the experience. If you want a rental experience that stands out. car rental miami luxury [url=https://luxury-car-rental-miami-pck.com]car rental miami luxury[/url] Save it, share it, don’t lose it for the area. It’s the easiest way to make your trip special. Luxury car rental Miami — drive the dream!

  13. Da installatore ho notato che molti rubinetti touchless hanno un tempo di flusso regolabile che spesso viene impostato su 60 secondi per evitare sprechi. Secondo voi qual è la durata media di funzionamento senza manutenzione su modelli con almeno 150 Post informativo

  14. I really appreciate the focus on parity in this article. It feels like the 2024 season could finally break the cycle of a few dominant teams controlling everything. With so much QB turnover, you never know which underdog might seize the moment Visit this link

  15. If you’ve ever been to Miami, you know it’s a city that demands style. I wanted to find a company that offered both quality cars and great service. Fortunately, I stumbled upon exactly what I was looking for. luxury car rental miami — I was genuinely impressed. No hard sales tactics, just honest advice. It made every journey feel like an adventure. If you’re looking for a car that matches the city’s energy. miami exotic car rentals [url=https://luxury-car-rental-miami-nwj.com]miami exotic car rentals[/url] Check the link for the full fleet and pricing for the area. If you want a luxury car in Miami — just use the link. Luxury car rental Miami — drive in style, create memories!

  16. And the car you drive plays a huge part in that experience. Some had the cars but not the service, others vice versa. Then I found a company that truly delivered. exotic car rental miami — Everything from sleek convertibles to powerful supercars. They helped me find the perfect car without any pressure. I enjoyed every moment behind the wheel. If you’re visiting Miami and want a car that matches the lifestyle. luxury car rental in miami [url=https://luxury-car-rental-miami-pck.com]luxury car rental in miami[/url] Check the link for the full fleet and pricing for South Beach. It’s the easiest way to make your trip special. Luxury car rental Miami — drive the dream!

  17. Постоянные конфликты с одноклассниками, а учителя закрывали на это глаза. И начали искать альтернативу. обучение онлайн для школьников — мы выбрали ту, где есть живое общение с учителями. Дочка сама составляет расписание. Пропали истерики и слёзы по утрам. Если ваш ребёнок страдает в обычной школе — не терпите. онлайн школа для ребенка 1 класс [url=https://shkola-onlajn-epn.ru]https://shkola-onlajn-epn.ru[/url] Сохраните, поделитесь, не потеряйте для региона. Это работает. Школа онлайн — образование без слёз и стресса!

  18. Miami is a city that demands attention, and your car is part of that statement. I wanted a car that was both stylish and fun to drive. That’s when I came across the perfect match. miami luxury car rental — the cars were incredible. They were professional, friendly, and truly helpful. I took the car out for a spin and it exceeded my expectations. If you want a car that turns heads and delivers excitement. rent a luxury car miami [url=https://luxury-car-rental-miami-tqk.com]rent a luxury car miami[/url] Check the link for the full fleet and pricing for South Florida. If you want a luxury car in Miami — just use the link. Luxury car rental Miami — live the experience!

  19. I wanted my trip to be memorable from the moment I hit the road. I wanted a car that was both stylish and fun to drive. That’s when I came across the perfect match. exotic car rental miami — Everything from high-end sports cars to elegant luxury sedans. The team made the whole process seamless. The car was a major part of why I enjoyed my trip so much. If you want a car that turns heads and delivers excitement. luxury rental cars miami [url=https://luxury-car-rental-miami-tqk.com]luxury rental cars miami[/url] All the details are there for South Beach. It’s the easiest way to elevate your trip. Luxury car rental Miami — live the experience!

  20. When I landed in Miami, I knew the city would be full of excitement. I wanted a rental company that offered more than just a car — I wanted a full experience. I found exactly what I was looking for. rent a luxury car miami — Every car was spotless, well-maintained, and ready to drive. The team was welcoming and professional. I drove a beautiful car throughout my stay. If you want a car that reflects the city’s energy. miami supercar rental [url=https://luxury-car-rental-miami-qhd.com]https://luxury-car-rental-miami-qhd.com[/url] Save it, share it, don’t lose it for South Florida. It’s the easiest way to make your trip unforgettable. Luxury car rental Miami — elevate your journey!

  21. Долго не могли решиться на смену школы. Мы поняли, что надо что-то менять. онлайн школа 10-11 класс — оказалось, что таких школ много. Дочка сама составляет расписание. Через три месяца она расцвела. Если ваш ребёнок страдает в обычной школе — не терпите. онлайн школа с государственной аккредитацией [url=https://shkola-onlajn-epn.ru]https://shkola-onlajn-epn.ru[/url] Сохраните, поделитесь, не потеряйте для нашего города. Это работает. Школа онлайн — образование без слёз и стресса!

  22. Miami is a city that demands attention, and your car is part of that statement. I researched several luxury car rental companies before my trip. That’s when I came across the perfect match. miami luxury car rental — the cars were incredible. They made sure I got the car that suited my needs perfectly. Every drive in Miami felt like an event. If you want a car that turns heads and delivers excitement. rent exotic cars in miami [url=https://luxury-car-rental-miami-tqk.com]https://luxury-car-rental-miami-tqk.com[/url] Check the link for the full fleet and pricing for Miami. If you want a luxury car in Miami — just use the link. Luxury car rental Miami — live the experience!

  23. I wanted to experience Miami in a way that felt truly premium. Not easy to find, but I eventually did. I found exactly what I was looking for. miami luxury car rental — Everything from high-end sedans to exotic sports cars. The team was welcoming and professional. Every trip became an event. If you’re planning a trip to Miami and want to add something special. miami car rental luxury [url=https://luxury-car-rental-miami-qhd.com]https://luxury-car-rental-miami-qhd.com[/url] Save it, share it, don’t lose it for Miami. It’s the easiest way to make your trip unforgettable. Luxury car rental Miami — elevate your journey!

  24. I wanted my trip to be memorable from the moment I hit the road. I researched several luxury car rental companies before my trip. That’s when I came across the perfect match. miami luxury car rental — the cars were incredible. They made sure I got the car that suited my needs perfectly. Every drive in Miami felt like an event. If you’re planning a trip to Miami and want to experience it the right way. miami supercar rental [url=https://luxury-car-rental-miami-tqk.com]miami supercar rental[/url] Check the link for the full fleet and pricing for South Beach. It’s the easiest way to elevate your trip. Luxury car rental Miami — live the experience!

  25. ギルガメッシュは会心とエネルギーの調整を先に決めると、遺物の更新順が分かりやすくなりました。編成では味方の行動順も確認して、必殺技を撃ちたい場面で火力をまとめるのがおすすめです。 無課金装備の組み合わせ

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注