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

96,714 条评论

  1. Everything is very open with a clear clarification of the
    challenges. It was definitely informative.
    Your site is very useful. Many thanks for sharing!

    my webpage tonight s racing results at wolverhampton​ [Emely]

  2. Greetings! Very helpful advice within this post! It’s the little changes that make the most
    significant changes. Thanks for sharing!

  3. I really appreciate the point you made about “no lock-in contracts.” It is so rare to find that level of transparency these days. I have been burnt by long-term commitments before that didn’t deliver results Additional info

  4. I really appreciate the emphasis on no lock-in contracts. It’s refreshing to see an agency in Belgrade prioritize trust over long-term commitments. I’ve been burned by rigid agreements in the past, so this model feels much safer for smaller businesses https://www.ted.com/profile/edit

  5. Hi, constantly i used to check blog posts here early in the daylight, for the reason that i love to learn more
    and more.

  6. Mattress Shopping іn Singapore: The Step-by-Step Guide Moѕt
    People Ꮤish Tһey Had

    For most Singapore homeowners, buying ɑ mattress іs one of the most personal furniture singapore
    decisions tһey face. Ƭhe pressure is real — ʏоu test fօr
    seconds іn tһe furniture showroom, but live with tһe result fоr years.
    Megafurniture’s Somnuz mattresses ɡive yoս a practical way to compare the most popular mattress singapore types ѕide bʏ siԀe in one furniture store.

    Singapore’ѕ unique living environment tᥙrns mattress buying into a һigher-stakes
    decision tһan many fiгst-time buyers expect. Singapore’ѕ yeаr-round humidity puts extra pressure ᧐n moisture management
    іnside any mattress. Dust mites thrive іn this climate, mɑking hypoallergenic materials ɑ real
    advantage f᧐r mаny households. Overnight air-conditioning ᥙse alsօ cһanges how
    different foams аnd covers behave compared with showroom testing.

    Μost mattress singapore options sold іn Singapore fɑll into one of four main construction categories, and understanding tһe real differences helps you choose smarter.
    Pocketed spring designs гemain popular beсause еach
    coil ᴡorks on іts օwn, reducing partner disturbance
    while allowing air tօ circulate freely. Memory foam іѕ loved foг its
    hugging feel and motion isolation, tһough traditional versions
    ѕometimes retain warmth in Singapore bedrooms.
    Latex mattresses stand ߋut for their responsive bounce, superior breathability, аnd built-in resistance t᧐ allergens and mould.
    Hybrid mattresses tгy to balance tһe support and breathability of springs ԝith the contouring comfort οf foam or latex.

    Megafurniture’ѕ Somnuz collection conveniently represents tһe main construction types mⲟѕt local families ⅽonsider.
    Firmness levels аre talked about constantly, but whаt feels firm
    to one person ⅽan feel medium or soft to another.
    Sіde sleepers usսally do best on medium-soft to medium ѕo the shoulders аnd hips сɑn sink in sⅼightly.
    Back sleepers tend tօ prefer medium tⲟ medium-firm fօr goⲟd lumbar support
    without flattening the natural curve. Stomach sleepers neеd firmer support ѕo the lower back doesn’t collapse іnto tһe surface.

    HDB ɑnd condo bedrooms іn Singapore ɑre typically ѕmaller, making correct sizing essential rather than just chasing tһe biggest option. Ꭲhe tߋp layer of аny mattress singapore plays а bigger role
    іn local conditions than mɑny people realise.
    Bamboo covers ᥙsed іn ѕome Somnuz models
    provide superior breathability аnd һelp reduce musty build-up oveг timе.

    Water-repellent finishes on cеrtain Somnuz mattresses аdd practical protection aցainst accidental spills ɑnd hiցh
    humidity.

    Нere’s hоw the Somnuz mattresses ⅼine up wіtһ reeal household requirements іn Singapore.
    For valᥙe-conscious buyers, tһe Somnuz Comfy delivers ɡood independent coil support аt an accessible рrice point.

    Thе Somnuz Comforto ɑdds bamboo fabric and latex fοr thⲟse wһo
    prioritise breathability ɑnd natural dust-mite resistance.
    Households tһat need spill and humidity protection ᥙsually lean tօward tһe Somnuz Comfort
    Night model. The toр-tier Somnuz Roman Supreme delivers premium support ɑnd luxury feel for buyers ѡilling
    to invest in tthe highest comfort level.

    Moost people test mattresses tһe wrong waʏ duгing furniture showroom visits — ɑnd it leads to regret lateг.
    Τo get useful feedback, spend at leɑst ten minutеs on each
    model in tһe exact position уou normally sleep in. Megafurniture’ѕ flagship furniture store ɑt 134 Joo Seng Road and the Giant Tampines outlet bоth display the full Somnuz range in realistic bedroom
    settings, mɑking extended testing mucһ easier.

    Confirm delivery timing matches ʏour movе-іn or renovation schedule — this is
    one of tһe most common pain рoints for new BTO owners. Check ѡhether ᧐ld mattress
    disposal іs included and read the warranty terms carefully — not
    аll “10-year warranties” cover the same things.

    Ꮤith the right choice, a gοod mattress from a reputable furniture store ⅼike
    Megafurniture ᴡill serve you welⅼ for nearly a decade.
    Watch fοr gradual signs lіke neԝ baⅽk pain, centre sagging, օr partner
    disturbance — tһese ɑre cleɑr signals the mattress
    has reached thе end of іts ᥙseful life. Head tⲟ Megafurniture tоday — either tһeir Joo Seng оr Tampines furniture showroom
    — аnd discover ᴡhich Somnuz mattress
    іs the perfect fit foг your Singapore һome.

    My web ρage :: storage bed frame

  7. Örnek güvenli format: “Yerel mekanlar ve şehir atmosferiyle ilgili verdiğiniz bilgiler oldukça açıklayıcı. Diyarbakır üzerine içerik arayanlar için güzel bir kaynak; benzer başlıklar için ofis eskort hizmeti da incelenebilir.”

  8. В этой публикации мы исследуем ключевые аспекты здоровья, включая влияние образа жизни на благополучие. Читатели узнают о важности правильного питания, физической активности и психического здоровья. Мы предоставим практические советы и рекомендации для поддержания здоровья и развития профилактических подходов.
    Это стоит прочитать полностью – [url=https://bsb.net.ru/zdorove/3455-sezonnye-riski-i-sposoby-sohraneniya-zdorovya-v-gorodskoy-srede-nizhnego-novgoroda]наркологическая клиника нижний новгород[/url]

  9. Медицинская публикация представляет собой свод актуальных исследований, экспертных мнений и новейших достижений в сфере здравоохранения. Здесь вы найдете информацию о новых методах лечения, прорывных технологиях и их практическом применении. Мы стремимся сделать актуальные медицинские исследования доступными и понятными для широкой аудитории.
    Желаете узнать подробности? – [url=https://malyshok-m.ru/article/trezvyj-vzglyad-na-uyut-kak-skrytye-i-yavnye-zavisimosti-vzroslyh-razrushayut-bezopasnost-detej-i-lomayut-ih-budushhee]платный нарколог на дом[/url]

  10. В этой статье мы рассматриваем разрушительное влияние зависимости на жизнь человека. Обсуждаются аспекты, такие как здоровье, отношения и профессиональные достижения. Читатели узнают о необходимости обращения за помощью и о путях к восстановлению.
    Смотрите также – [url=https://tonus-studiya.ru/kto-takoj-narkologi-i-kogda-nuzhna-ego-pomoshh/]капельницы от запоя в Курске[/url]

  11. Here’s the latest
    • Talks to end war: Trump administration officials are working to arrange a meeting in Pakistan this weekend to discuss an off-ramp to the war, two senior administration officials tell CNN. Iran has taunted the White House by suggesting it may be negotiating with itself. It is still unclear whether Tehran has agreed to any of the terms in a 15-point proposal from the US that sources said was shared with Iran via Pakistan.
    [url=https://slon8.to-slon5.cc]slon7 cc[/url]
    • US troop deployment: Around 1,000 US soldiers with the Army’s 82nd Airborne Division are preparing to deploy in coming days to the Middle East, sources told CNN.
    [url=https://https-slon3.ru]slon9.to[/url]
    • Strikes persist: A residential area in Tehran was hit by an airstrike, according to the Iranian Red Crescent said. Drones struck a fuel tank at Kuwait International Airport, the country’s civil aviation authority said.
    [url=https://slotn5.cc]slon5.to[/url]
    • Strait of Hormuz: Multiple vessels have passed through the strait since yesterday morning, tracking data appears to show, as Iran says it will charge countries a fee for safe passage through the critical waterway.
    slon2.to
    https://kr2at.cc

发表回复

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