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

186,716 条评论

  1. TripScan: ваш надежный навигатор в мире путешествий
    [url=https://tripscan77c.cc]трипскан [/url]
    Современный туризм давно перестал быть просто покупкой билетов и бронированием отеля. Сегодняшняя поездка — это сложный механизм, состоящий из десятков деталей: трансферы из аэропортов, регистрация на рейсы, подтверждение броней, страховые полисы, стыковки междугородних автобусов, адреса квартир посуточной аренды и списки мест, которые обязательно нужно увидеть. Удержать всю эту информацию в голове невозможно, а хранить ее разрозненными файлами в почте и заметках — значит постоянно рисковать что-то упустить.

    Именно для решения этой проблемы создан TripScan — сервис мониторинга поездок и путешествий, который берет под контроль каждый этап вашего пути.

    Полный мониторинг от двери до двери
    [url=https://tripscan77c.cc]трипскан официальный сайт [/url]
    Забудьте о панике в аэропорту, когда вы судорожно ищете номер терминала, или о неловких поисках распечатанного подтверждения бронирования в тесном холле гостиницы. TripScan собирает все данные о вашем путешествии в единую цифровую экосистему.

    Просто внесите детали поездки в сервис, и он автоматически выстроит хронологию событий:
    [url=https://tripscan77c.cc]tripscan сайт [/url]
    * Транспорт: отслеживание статуса авиарейсов в реальном времени с мгновенными уведомлениями об изменениях, информация о выходе на посадку, номерах поездов и автобусов.
    * Проживание: контакты отелей и апартаментов, время заезда и выезда, условия отмены, ваучеры и коды бронирования.
    * Документы: безопасное хранение электронных копий паспортов, виз, страховок (включая экстренные телефоны ассистансов) и водительских удостоверений.
    * Логистика: маршруты трансфера, билеты на экскурсии, запланированные встречи и аренда автомобилей.
    * Финансы: учет предоплат, депозитов и оставшихся лимитов по бюджету поездки.
    [url=https://tripscan77c.cc]tripscan зеркало [/url]
    Сервис работает как ваш личный диспетчер. Если рейс задерживается, TripScan тут же оповестит вас и предложит скорректировать время подачи такси или предупредить отель о позднем заезде. Вы больше не зависите от нестабильного интернета в роуминге в поиске нужных писем — вся критически важная информация всегда доступна в приложении даже в офлайн-режиме.

    Управляйте всеми поездками в одном месте

    TripScan — это не только инструмент для текущего отпуска, но и удобный архив ваших приключений. В личном кабинете хранится история всех перемещений. Это невероятно удобно для решения практических задач:

    * Быстро найти квитанцию за перелет годовой давности для оформления налогового вычета или отчета о командировке.
    * Вспомнить название того уютного кафе во Флоренции или точный адрес квартиры в Батуми, куда хочется вернуться.
    * Проанализировать свои туристические привычки, общую сумму трат на путешествия и посещенные страны.
    [url=https://tripscan77c.cc]трипскан вход [/url]
    Кроме того, сервис позволяет вести совместный мониторинг. Планируете семейный отдых или поездку с друзьями? Предоставьте доступ к маршруту попутчикам. Теперь каждый участник группы видит актуальное расписание, знает, где хранятся общие документы, и получает важные уведомления одновременно с вами.

    Ничего не останется без внимания

    https://tripscan77c.cc

    tripscan

  2. Great post. I was checking constantly this weblog and I’m
    impressed! Extremely useful info specially the remaining phase :
    ) I deal with such information a lot. I was
    seeking this particular info for a long time.
    Thank you and good luck.

  3. Доброго!
    Ищете ежедневные коды Roblox или обновленные коды Roblox для любимого плейса? У нас есть все актуальные игровые коды, популярные Roblox коды и коды на бонусы в играх. Читайте наши информативные игровые гайды, изучайте секреты игр и смотрите прохождения игр. Мы собрали чит-коды для игр, коды для мобильных игр и коды для ПК игр для всех геймеров. Мы расскажем, как активировать коды Roblox, чтобы вы могли использовать новые коды Roblox и Роблокс коды. Открывайте наш список кодов Roblox, смотрите все коды Роблокс и забирайте крутые коды на валюту Roblox, коды на скины Roblox и коды на предметы Roblox.
    Подробная информация на сайте https://game-zoom.net
    обновленные коды Roblox, актуальные коды Roblox, Roblox промокоды
    все коды Роблокс, [url=https://game-zoom.net]как активировать коды Roblox[/url], актуальные коды Roblox
    Всего наилучшего и хорошего геймплея!

  4. به شکل خلاصه

    برای اون گروه از کاربرا که

    فعالیت‌های شرطی

    قصد فعالیت دارن

    اینجا

    می‌تونه انتخاب مناسبی باشه

    ارزش بررسی داشته باشه

    جالبه که

    سرویس‌هایی مثل

    enfejɑronline آنلاین

    و

    sibbеt آنلاین

    پیشرفت قابل توجهی داشتن

    جمع‌بندی اینکه

    خیلی خوب بود

    و

    حتما

    استفاده دوباره میکنم

    Stop by my site: نتیجهگیری: تبدیل دانش به سود

  5. Unlock limitless financial savings at Kaizenaire.ϲom,
    Singapore’s primary collector ⲟf promotions, deals, ɑnd exciting occasions from
    preferred brands.

    Singaporeans neᴠer miѕs out on a beat ᴡhen іt
    concerns deals, prospering іn their city’s environment as
    the beѕt shopping heaven.

    Singaporeans enjoy laying օut metropolitan landscapes іn note pads, and keep іn mind to stay upgraded on Singapore’ѕ ⅼatest
    promotions and shopping deals.

    ComfortDelGro supplies taxi ɑnd public transport solutions, appreciated
    Ьy Singaporeans fοr theiг reputable adventures and considerable network аcross the city.

    Axe Brand Universal Oil supplies medicated oils
    fߋr discomfort alleviation leh, loved ƅy Singaporeans for
    theіr efficient solutions іn everyday pains օne.

    Koi Thé delights ᴡith milky teas and goldden bubbles, beloved fⲟr premium components and regular higһ quality thrоughout outlets.

    Wah, why wait siа, get on Kaizenaire.com typically tߋ grab tһe hottest promotions fгom Singapore’ѕ tⲟp brand
    names mah.

    My web ⲣage … promotions singapore

  6. I like the valuable info you provide in your articles.
    I’ll bookmark your blog and check again here regularly.
    I am quite sure I will learn plenty of new stuff right here!

    Best of luck for the next!

  7. Thanks for the marvelous posting! I definitely enjoyed reading
    it, you are a great author.I will be sure to bookmark your blog and may come back from now on. I
    want to encourage you to ultimately continue your great
    writing, have a nice afternoon!

  8. Gates of Olympus offers an awe-inspiring journey into the realm of the gods, where stunning visuals and a rich color palette create an atmosphere worthy of divine power. The celestial theme is beautifully executed, making every spin feel like a step closer to unlocking mythical treasures. Your best shot is during the Holly Jackpot, which happens every Wednesday, Friday, and Saturday evening. Outside of those times, wins are totally random. But if you play during the Jackpot Race, your chances of winning go up a lot so don’t miss it. Gates of Olympus is fully optimized for mobile play, ensuring that players can enjoy the game on their smartphones or tablets without any compromise in quality or features. The game runs smoothly on various mobile devices, both on Android and iOS platforms, allowing players to enjoy the excitement of Gates of Olympus anytime and anywhere.
    https://pgs.com.sg/mostbet-az-90-login-yeni-giris-usullari/
    VideoGPT can create videos from text descriptions. They analyze the text to generate relevant visuals, animations, or scenes, making content creation faster and easier. Create realistic videos, films, and short videos with stunning Al features, including an anime AI video generator, cinematic effects, realistic voiceovers, and much more. Easily remove backgrounds from your videos and images. Add new backgrounds or keep them transparent for various video needs. Choose from a wide range of stock backgrounds to enhance your video appearance. The output that you export using the application will have maximum quality of 1080p and can be used for various purposes. This comes from the application’s ability to export the video as a video or as a green screen. So if you want to add it to a specific video, you just need to create the product as a video. If you are a professional creator, there are many ways to use the product with a green screen.

  9. Hi there! I could have sworn I’ve been to this website
    before but after looking at some of the posts I realized it’s new
    to me. Anyways, I’m definitely pleased I discovered it and
    I’ll be book-marking it and checking back regularly!

  10. These cookies enable key functionality of the website and help to keep its users secured. They are automatically saved in the browser and cannot be disabled. Yes, the modded version of Alight Motion (am) for your iOS iPhone is safe and malware-free to download and use for animation projects without a watermark. To install the modded version, follow my installation guidelines, which include particular instructions in the article. 6Play Alight Motion Preset with NoxPlayer on PC easier! Alight Motion PC is a graphics software for your smartphone, and it’s significant since it’s the first professional motion graphics app for portable devices. The use of cell phones is becoming increasingly sophisticated. Alight Motion offers professional animation, video compositing, video editing, and effects, among other services. Alight Motion has so many capabilities that it has become more than simply a standard video editing programme.
    https://www.blackhatprotools.info/member.php?280567-jasonwalker
    “VideoPad Video Editor is an affordable, entry-level video editing application that’s particularly powerful for creators who want to publish their videos to YouTube or Facebook.”PCWorld People who are just starting to edit videos or are good at it know about VideoPad Video Editor by NCH Software. VideoPad software is easy for people to make refined videos. It is known for having an easy-to-use interface and basic editing tools. Is it the best choice for everyone, though? The program couldn’t be easier if you look at competing products. VideoPad Free Version includes support for some of the most popular video compression formats and can create some cool looking end videos with the excellent effects and transitions included. VideoPad Editor is a world-class video editor. The tool offers a wide range of options to edit videos with ease. The output video quality is top-notch. You can upload its videos on all major platforms, like YouTube, Facebook, Instagram, etc., without hesitation.

  11. Fishin’ BIGGER Pots Of Gold Fish up an absolute whopper in Big Bass Bonanza Slot by Pragmatic Play. It’s the seafaring slot where the catch of the day is just a spin away! Big Bass Bonanza Hold & Spinner is available on tablet, mobile, or desktop devices and has bet levels of 10 p c to $ €250 per spin. When betting regularly in this mode, the game has a default RTP of 96.07%, rising to 96.09% when activating the Ante Bet. The Ante Bet increases the stake by 50% for an extra chance of Scatter symbols. The other way of possibly playing Big Bass Bonanza Hold & Spinner is buying free spins or the Hold & Spinner. In both cases, the RTP is 96.07%, keeping in mind lower return models are available, though all info is displayed on the paytable. This section is partly a trip down memory lane, part discovery. Big Bass Bonanza Hold & Spinner has not one but two bonus rounds to offer, free spins and the Hold & Spinner.
    https://motobuy580.com/gates-of-olympus-welkomstbonus-een-complete-gids/
    CapCut, developed by ByteDance (the creators of TikTok), is one of the most popular video editing apps. It’s well-loved for its simplicity and powerful tools that cater to both beginners and experienced editors. The application’s payment model includes a freemium option, alongside an InShot Pro Unlimited subscription. This gives users access to complete features and paid editing materials like stickers, filter packages, etc. This also enables watermarks and advertisements to be removed automatically. There’s no in-app support, but watching a few comprehensive YouTube tutorials will be enough for most students to get going. They might need some help with ideas, though; a content gallery would be a nice addition for ideas for classroom use. Teachers should be aware that the app lacks safeguards to ensure that students aren’t using copyrighted images or videos. Although the music tracks available inside the platform advise attribution, students also have the option of importing music from iTunes. Be sure to equip students with knowledge of proper copyright guidelines before they publish their content publicly.

  12. Hi, I do believe this is an excellent website. I stumbledupon it
    ;) I’m going to return yet again since I book
    marked it. Money and freedom is the greatest way to change,
    may you be rich and continue to help other
    people.

  13. Слушайте кто искал участок То вообще непонятно где смотреть Соседи какие Короче, работает быстро и бесплатно — публичная кадастровая карта новая с 3D-видом Увидел границы и соседей В общем, там и карта и данные — реестр карта [url=https://publichnaya-kadastrovaya-karta-abc.ru]https://publichnaya-kadastrovaya-karta-abc.ru[/url] Не мучайтесь с росреестром Перешлите тому кто ищет участок

  14. звоните круглосуточно по телефону горячей линии клиники: наши специалисты готовы оказать необходимую помощь в решении проблемы алкогольной зависимости.
    Подробнее тут – [url=https://vyvod-is-zapoya-sochi20.ru/]вывод из запоя цена сочи[/url]

发表回复

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