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

121,065 条评论

  1. Люди подскажите Брат потерял человеческий облик Соседи уже вызвали участкового Скорая не приедет на такой вызов Короче, спасла только госпитализация — вывод из запоя стационар с круглосуточным наблюдением Врачи и медсёстры 24/7 В общем, вся инфа по ссылке — цена вывода из запоя в стационаре [url=https://alkogolizm.vyvod-iz-zapoya-v-staczionare-nizhnij-novgorod-knd.ru]цена вывода из запоя в стационаре[/url] Стационар — это единственный выход Это может спасти жизнь

  2. HIThttps://hitclubs1.com/ tạo nên trải nghiệm giải trí trực tuyến có nhịp xử lý nhanh, giao diện hiện đại và khả năng thích ứng tốt trên cả web lẫn thiết bị di động.
    bbc

  3. Get an Animiz account as the beginning of making a cartoon animation video In its simplest form, animation is simply moving images. This is why the idea of drawing multiple pictures onto a notebook and flipping the pages to simulate movement is so relatable. ‍Adobe Animate lets you create 2D animations for various formats, like banner ads, video games, and mobile apps. Its deforming tools support design motion graphics for trickier subjects like animated fire and clouds that must change shape and size. And tweening handles the movement between keyframes, creating new frames that move vectors as subjects flex and change. No any designing skills? No any animation creating experience? Animiz powerful animation effects help you out. There are 300+ splendid animation effects available for you. Choose and apply to your video. What you see is what you get. Easily create your own animation with the combination of entrance, emphasis and exit effects. Not only that, there are various kinds of transition animation effects for your scenes, improving the fluency and attraction of your video.
    https://linuxfellas.com/500-casino-uk-review-a-top-choice-for-online-players/
    Fish symbols are Money symbols, and they are able to land while the Free Spins Bonus is being played. Big Bass Bonanza hooks players with its simple yet engaging gameplay, offering a refreshing take on the slot genre with its fishing theme. The game’s popularity is buoyed by its appealing graphics, upbeat soundtrack, and the potential for substantial wins during the free spins bonus round. It’s a well-balanced game that suits both casual players and serious anglers looking for a big catch. Plus, Lucky Clover is not a very popular slot. Even though there are fewer variants when playing live dealer blackjack, a win stop. Want to take a break from playing the game, what is the progressive jackpot rtp in the bigger bass bonanza game and several other automatic stops. Fish symbols are Money symbols, and they are able to land while the Free Spins Bonus is being played.

  4. After uploading your video, you can choose the clip durations and trim your long video before converting. CapCut’s auto video editor will then analyze and automatically edit it into multiple short clips. To expand your global reach, subtitles will be added automatically to each short clip. Just upload your audio file or select one of the royalty-free music tracks from the music library and adjust timing and volume in the editor. Chat GPT itself isn’t really for video, but many video editors are using it as a foundation for executing editing tasks faster than before. Instead of having to find the right Chat GPT inquiries, an AI Editor already does this for you and will deliver exactly what you need. AI video creators are using this for AI transcription, automated cuts, and more. Yes, there are many different types of AI video software out there that can edit videos for you. If you want to generate videos from a script, you can use Synthesia. If you want to create multiple short videos from your existing videos automatically, you can use Vizard.ai. We are the easiest AI solution out there that can edit social-ready videos for you.
    https://www.top10menage.ca/?p=57069
    iFaceDance : AI Image Animator Aviart: AI Photo Generator The app that makes portraits move is YouCam Video! The AI video editing app can turn any portrait into a moving picture with its Image-to-Video feature, available for Android and iPhone! Upscale Videos up to 8K and interpolate frames to 120fps. The Krea and Topaz Video upscalers can restore old videos, turn phone captures into professional footage, or make regular videos ultra slow-mo. AI Video & Image Generator! Follow these 4 steps to bring your images to life using YouCam Video: ImgPlay is another app you can use to animate photos. Think of it like a mashup between Motionleap and Werble. It creates ready-to-use animated photos for the web, and has advanced, easy-to-understand controls. Unfortunately, it also sticks a watermark on your image—one that you can’t remove unless you upgrade to a full account.

  5. Люди помогите советом Задолбался я уже искать нормальную кухню То фасады кривые Короче, единственные кто не наваривается — кухни спб на заказ с фурнитурой Blum Проект бесплатно В общем, смотрите сами по ссылке — изготовление кухни на заказ в спб [url=https://kuhni-spb-qmz.ru]https://kuhni-spb-qmz.ru[/url] Проверяйте производителя по этому списку Сам мучался теперь делюсь

  6. В отличие от государственных диспансеров, где нужно лично являться на приём и вставать на учёт, наша выездная служба гарантирует полную анонимность. Медицинская деятельность осуществляется строго по лицензии, все необходимые документы и сертификаты специалистов можно посмотреть в фотогалерее на сайте. Для многих зависимых людей вызов специалиста домой становится первым и самым важным шагом к выздоровлению, ведь признать проблему публично готов далеко не каждый. За долгие годы лечения алкоголизма и наркомании наши наркологи сталкивались с различными ситуациями, поэтому врач быстро подберет оптимальную для конкретного пациента схему терапии. Продолжая использовать наш сайт, вы соглашаетесь с пользовательским соглашением и даёте согласие на обработку персональных данных, однако эта информация применяется исключительно для организации выезда и составления индивидуального плана лечения.
    Изучить вопрос глубже – [url=https://narkolog-na-dom-v-lyubercah14.ru/]narkolog-na-dom-moskovskoy-oblasti[/url]

  7. Решение вызвать бригаду должно приниматься на основе четкого анализа симптомов. Если вы замечаете у близкого стойкое отвращение к еде, неукротимую рвоту или жалобы на мучительные боли в груди, это сигнал о токсическом поражении жизненно важных органов. В подобных случаях без профессиональной диагностики и инфузионной терапии справиться с отравлением практически невозможно.
    Исследовать вопрос подробнее – [url=https://narkolog-na-dom-v-lyubercah14-2.ru/]vyzov-narkologa-na-dom-moskovskaya-oblast[/url]

  8. Наркологическая помощь особенно важна, когда запой повторяется не первый раз, употребление спиртного носит систематический характер, а человек уже пытался бросить пить, но снова срывался. В таких случаях капельница и детоксикация облегчают ломку, но не вылечивают алкогольную зависимость полностью. Поэтому профессиональный центр предлагает не только срочный вывод из запоя, но и лечение алкоголизма, кодирование, психотерапию, реабилитационный курс, мотивационную беседу, поддержку родственников и восстановительную терапию после интоксикации.
    Получить дополнительную информацию – [url=https://vyvod-iz-zapoya-v-novorossijske1.ru/]вывод из запоя круглосуточно в новороссийске[/url]

  9. С пациентом работают профильные специалисты, которые оценивают состояние и подбирают безопасный план помощи.
    Углубиться в тему – [url=https://vyvod-iz-zapoya-v-anape5.ru/]вывод из запоя круглосуточно анапа[/url]

  10. Top Ads A TikTok video editor is a tool that lets you trim, crop, enhance, or subtitle videos before posting them to TikTok. Whether you’re creating content on desktop, mobile, or using AI — these editors help make your videos viral-ready. Videoshop is a feature-rich video editing app that offers a wide range of tools for customizing and enhancing videos. Users can access a free version of Videoshop or choose from subscription plans starting at $3.49 per month for the “Videoshop Pro” plan, unlocking additional features and removing watermarks. It is very easy to download the Mojo TikTok video editor. All you have to do is go to your iOS or Android app store and enter the name of the tool you are looking for in the search bar. As TikTok is a mobile app, the TikTok video editor by Mojo is only available on your smartphone. Check that the tool you are interested in is compatible with your operating system!
    https://baagartools.com/explore-uk-winner-casino-slots-for-endless-fun/
    Unleash your inner god, goddess, or creature of legend at COSI After Dark: Mythology. On November 13, we’re bringing ancient stories to life with hands-on fun and a touch of magic. Tiktok could be in real trouble in the U.S. after the House of Representatives voted in favor of the Protecting Americans From Foreign Adversary Controlled Applications Act. This act would require the app to be sold by its parent company, Bytedance, or face a federal ban. Bisineer’s 2016 animated short let me not be mad, commissioned by Film London, Arts Council England in association with London Shakespeare Centre at King’s College, London, screened at festivals across the world and she animated for Finding Altamira, director Hugh Hudson’s 2016 feature film. She has received numerous awards, including the Judge’s Prize for Animation Film at the East West Arts Award, the David Gluck Memorial Bursary, The Discerning Eye Drawing Prize, and the Man Drawing Prize. Prior to joining the CCA faculty, Bisineer taught in the UK at the Royal College of Art, University for the Creative Arts, and University of Portsmouth.

  11. Those who played the original will encounter familiar symbols in the paytable. It includes the low-paying playing cards, followed by Fish, Tackle Boxes, Fishing Rods, Dragonflies, and Floaters. There’s also a new icon on the list, represented by the Fishing Boat. Finally, the Fisherman returns to the reels as the Wild, appearing only during Free Spins and replacing other symbols except for Scatters. As usual, Scatters have the role of triggering the Free Spins round. If you can hook out at least three fish scatters, this will trigger the bonus rounds where the bearded fisherman can appear. He will spice things up by giving you all the fish money symbols. The symbols are cleverly designed around a fishing theme, with higher-paying symbols including floats, fishing rods, dragonflies, tackle boxes, and, of course, bass.
    https://silveraenterprises.com/256/blazespins-casino-a-review-for-uk-players/
    Get Alight Motion Mod APK to enjoy Ads-free Premium features free of cost. Alight Motion Pro APK Latest version available now! No watermark, Time remapping, no lagging, ad-free experience, Batch editing, all effects are accessible, Zoom Out, Blur background, Zoom in, Motion Control, Blending modes, and many more. To enjoy all these features, download the modded version of Alight Motion from a trusted website. This is a brand-new application. Alight Motion Pro (Mod) is the first pro Motion graphics app for your smartphone, bringing you professional-quality animation, video editing, motion graphics, visual effects, and video compositing. The Alight Motion Mod APK is the modified and advanced version of the Standard app. It has gained the title of best free video editing app and has opened the gate of a world where incredible editing possibilities wait for you. It offers an ad-free experience with unlocked premium filters, unique effects, audio integration, advanced motion design features, and 100% security.

  12. Информация об обращении не передается третьим лицам, а детали лечения обсуждаются только с пациентом.
    Получить больше информации – [url=https://vyvod-iz-zapoya-v-koroleve14-2.ru/]вывод из запоя на дому цена[/url]

  13. Помощь может включать консультацию, детоксикацию, стационар и дальнейшее сопровождение по показаниям.
    Изучить вопрос глубже – [url=https://vyvod-iz-zapoya-v-koroleve14-1.ru/]вывод из запоя на дому королев[/url]

  14. Слушайте кто сталкивался Близкий человек уже 10 дней в запое Соседи уже вызвали участкового В диспансер тащить — последнее дело Короче, спасла только госпитализация — вывести из запоя в стационаре анонимно и безопасно Врачи и медсёстры 24/7 В общем, телефон и цены тут — вывод из запоя наркология [url=https://lechenie.vyvod-iz-zapoya-v-staczionare-nizhnij-novgorod-elm.ru]https://lechenie.vyvod-iz-zapoya-v-staczionare-nizhnij-novgorod-elm.ru[/url] Не ждите пока станет хуже Это может спасти жизнь

  15. Solid ideas! One aspect I’d add is optimizing your move name/thumbnail around present day activity patches—click-by way of jumps while it suits trending seek phrases. I compiled a list for this plus retention approaches here: click for more info

  16. Привет всем!
    Масштабное поисковое продвижение сайтов охватывает тысячи страниц больших интернет-магазинов и порталов. Мы автоматизируем процессы оптимизации для обработки большого объема данных и контента ресурса. Семантическое ядро расширяется за счет выявления новых перспективных кластеров запросов пользователей. Это позволяет захватывать долю рынка в смежных тематиках и увеличивать общий трафик сайта. Ваш бизнес масштабируется вместе с ростом видимости в поисковых системах интернета глобально.
    Самая полезная информация на сайте – https://linkbooster.space/
    комплексное seo продвижение, продвижение сайта товаров, продвижение ссылками
    продвижение сайтов, продвижение сайтов, раскрутка сайтов заказать
    Всего наилучшего и роста в топе!

  17. Помощь может включать консультацию, детоксикацию, стационар и дальнейшее сопровождение по показаниям.
    Узнать больше – [url=https://vyvod-iz-zapoya-v-lyubercah14-4.ru/]нарколог вывод из запоя[/url]

  18. Снятие запоя – это не только прекращение приема спиртных напитков, но и целый комплекс мероприятий, включающий очищение и восстановление организма, а также нормализацию общего состояния больного. В современных условиях наркологическая клиника может предложить вывод из запоя на дому, лечение запоя в стационаре, капельницу, детоксикацию, медикаментозный курс, психологическую помощь, кодирование, реабилитацию и дальнейшее сопровождение семьи. Такой подход позволяет не просто вывести человека из тяжелого периода, а определить причины зависимости, подобрать индивидуально эффективное лечение и снизить вероятность повторного срыва.
    Детальнее – [url=https://vyvod-iz-zapoya-v-anape2.ru/]срочный вывод из запоя[/url]

  19. Распознать критическое состояние, требующее участия профессионалов, можно по характерным признакам. Если у близкого наблюдается расстройство сознания, неадекватное поведение или резкие скачки артериального давления, медлить больше нельзя. В таких случаях необходима экстренная помощь врача-психиатра, ведь длительное воздействие токсинов может закончиться отказом жизненно важных органов. Вызвать нарколога на дом в Москве и области нужно при первых же угрозах, не дожидаясь усугубления ситуации. Наши специалисты готовы провести лечение запоя и снятие ломки немедленно.
    Выяснить больше – https://narkolog-na-dom-v-lyubercah14-1.ru

  20. Вывод из запоя в Королеве требуется, когда человек несколько дней употребляет алкоголь, не может остановиться, плохо спит, испытывает тревогу, тошноту, тремор, слабость, потерю аппетита и признаки похмельного синдрома. В такой момент главное — не пытаться лечить запойное состояние случайной дозой лекарственных средств, а обратиться к врачу. Наркологическая клиника подбирает лечение индивидуально: учитываются возраст пациента, срок употребления спиртного, стаж алкоголизма, наличие хронических заболеваний, самочувствие, риск развития осложнений и желание больного начать путь к трезвости.
    Получить больше информации – [url=https://vyvod-iz-zapoya-v-koroleve14.ru/]vyvod-iz-zapoya-v-koroleve[/url]

发表回复

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