首页 \ 问答 \ 限制python多处理中的总CPU使用率(Limit total CPU usage in python multiprocessing)

限制python多处理中的总CPU使用率(Limit total CPU usage in python multiprocessing)

我使用multiprocessing.Pool.imap在Windows 7上使用Python 2.7并行运行多个独立作业。使用默认设置,我的总CPU使用率与Windows任务管理器测量的100%挂钩。 这使得我的代码在后台运行时无法做任何其他工作。

我已经尝试将进程数量限制为CPU数量减1,如如何限制Python使用的处理器数量所述

pool = Pool(processes=max(multiprocessing.cpu_count()-1, 1)
for p in pool.imap(func, iterable):
     ...

这确实减少了正在运行的进程的总数。 但是,每个过程只需要更多的周期来弥补。 所以我的总CPU使用率仍然是100%。

有没有办法直接限制总CPU使用率 - 而不仅仅是进程数量 - 或者失败了,是否有任何解决方法?


I am using multiprocessing.Pool.imap to run many independent jobs in parallel using Python 2.7 on Windows 7. With the default settings, my total CPU usage is pegged at 100%, as measured by Windows Task Manager. This makes it impossible to do any other work while my code runs in the background.

I've tried limiting the number of processes to be the number of CPUs minus 1, as described in How to limit the number of processors that Python uses:

pool = Pool(processes=max(multiprocessing.cpu_count()-1, 1)
for p in pool.imap(func, iterable):
     ...

This does reduce the total number of running processes. However, each process just takes up more cycles to make up for it. So my total CPU usage is still pegged at 100%.

Is there a way to directly limit the total CPU usage - NOT just the number of processes - or failing that, is there any workaround?


原文:https://stackoverflow.com/questions/42103367
更新时间:2022-02-28 16:02

最满意答案

这完全属于如何处理子程序中的错误的问题。

对此进行了很好的讨论,但我现在找不到这些帖子。

原则上,这些是处理子例程中的错误的方法

  • 返回码,其中一些表示错误

  • 返回“特殊”值,如Perl中的undef

  • 抛出异常,Perl中的设备就会die

调用者要么检查返回,要么测试undef ,或使用eval来捕获和处理die 。 什么是最合适的完全取决于上下文和代码的作用。

我认为在现代语言中没有太多理由限制指示错误的“代码”(如负值)。 首先,要么干涉合法的回报,要么限制它们通过指针/引用,这是一个重大的设计决定。

返回undef通常是一种很好的中途方法,特别是在代码不太复杂的情况下。 它表示sub的某些“失败”,以执行它的意图。 然而,即使在最小的子中, undef也可能适合于表示不可接受的结果 。 然后,如果它也用于输入错误,我们就有区分这些错误的问题。

在简单die上使用Perl抛出异常会增加更多可能性。 在复杂的代码中,您可能希望编写(或使用)一个错误处理类,该类模仿具有它的语言的异常处理支持,然后抛出它。

my $error_obj = ErrorHandlingClass->new( params );

... or die $error_obj;

然后调用代码可以分析对象。 这将是最有条理的方式。

一个很好的简单例子是Path :: Tiny ,它的源代码中有自己的Path::Tiny::Error

同样,在任何一种特定情况下适用的内容取决于该应用的细节。


关于直接问题的一些评论。

die的无信息消息强调了返回什么的困境(它告诉我们什么都失败了)。 但在这种情况下,我们如何使失败提供信息?

请注意,如果sub返回0或空字符串,则表示or导致die 。 如果我们用// (defined-or)替换它,那么在undefdie ,如果undef也可能表示结果不好,我们仍然无法打印特定的消息。

因此,在这种情况下,您可能希望函数在输入错误时使用合适的消息。

这样做可以进行调试。 如果代码需要能够恢复,那么您最好返回更多结构化信息 - 抛出(或返回)您编写的错误处理类的对象。 (作为一种临时的止损措施,你可以解析die的信息。)

至于古老的纪律检查问题, die是一个很好的工具。 没有“ 简单的子 ”是不值得的 - 你不想继续犯错误,所以die也没关系。 在复杂的项目中,错误处理更复杂,因此我们需要更多的工具和结构,而不是更少。

回想一下异常“冒泡”,如果未处理则向上传播调用堆栈,并且die也是如此。 这可以很好地用于调试,而不需要每次调用都有eval 。 最后,大部分都是调试的一部分。

这没有“最佳实践”。 但缺席的die至少是合理的。


This falls squarely under the question of how to deal with errors in subroutines in general.

There have been good discussions on this but I just can't find those posts now.

In principle, these are ways to handle errors in subroutines

  • return codes, some of which indicate errors

  • return "special" values, like undef in Perl

  • throw exceptions, and a device for that in Perl is die

The caller either checks the return, or tests for undef, or uses eval to catch and handle the die. What is most suitable depends entirely on the context and on what the code does.

I don't see much reason in modern languages to be restrained to "codes" (like negative values) that indicate errors. For one thing, that either interferes will legitimate returns or it constrains them to go via pointer/reference, which is a big design decision.

Returning undef is often a good middle-of-the-road approach, in particular in code that isn't overly complex. It indicates some "failure" of the sub to perform what it is meant to. However, even in the smallest of subs undef may be suitable to indicate a result that isn't acceptable. Then if it is also used for bad input we have a problem of distinguishing between those errors.

Throwing an exception, based in Perl on the simple die, adds more possibilities. In complex code you may well want to write (or use) an error-handling class that mimics exception handling support from languages that have it, and then throw that.

my $error_obj = ErrorHandlingClass->new( params );

... or die $error_obj;

Then the calling code can analyze the object. This would be the most structured way to do it.

A nice and simple example is Path::Tiny, with its own Path::Tiny::Error found in its source.

Again, what is suitable in any one particular case depends on details of that application.


A few comments on direct questions.

The dilemma of what to return is stressed by the information-free message in die (it tells us nothing of what failed). But how do we make the failure informative, in this case?

Note that your or results in a die if the sub returns 0 or an empty string. If we replace it with // (defined-or), so to die on undef, we still can't print a specific message if undef may also indicate a bad result.

So in this case you may want the function to die on bad input, with a suitable message.

That would do it for debugging after there's been a problem. If the code needs to be able to recover then you'd better return more structured information -- throw (or return) an object of an error handling class you'd write. (As an ad hoc stop-gap measure you can parse the message from die.)

As for the age-old question of discipline to check returns, a die is a good tool. There is no "simple sub" that is unworthy – you do not want to proceed with an error so it's OK to die. And in complex projects error handling is more complex, so we need more tools and structure, not less.

Recall that exceptions "bubble up", propagate up the call stack if unhandled, and so does die. This can be used nicely for debugging without having eval on every single call. In the end, most of this is a part of debugging.

There is no "best practice" for this. But a default of die-ing is rather reasonable.

相关问答

更多
  • 作为前言,我花了3年的时间为一家大型金融公司设计和实现了一个非常复杂的Perl命令行工具集。 下面的想法基本上是我们团队设计准则的一部分。 用户界面 命令行选项:尽可能多地使用默认值。 任何超过2个选项的命令都没有位置参数。 有可读的选项名称。 如果命令行长度是非交互式调用的关注点(例如,某些未命名的传统shell在命令行上有短时间限制),请提供简短的别名 - GetOpt :: Long允许轻松使用。 至少,在'-help'消息中打印所有选项的默认值。 更好的是,打印所有选项的“当前”值(例如,如果参数和 ...
  • 我没有使用它,但上周在Caml团体上的消息提到了吉祥物 。 它看起来是你以后的样子。 我不确定尾递归标准; 上述项目的作者没有提及他们,但是提到了插件功能。 或者,使用-dlinear编译(对于ocamlopt[.opt] )将生成线性化代码,提到该函数是否是尾部调用。 -annot也-annot产生尾部呼叫信息,但除了变更日志 (它已在3.11.0中添加)之外,我找不到任何参考。 它以什么方式标记尾部呼叫,它不会做相反的事情,标记非尾部呼叫(或者也许有办法?)。 下面是一个名为sum的函数的输出示例, l ...
  • 我最终使用上面的第一个解决方案 - 运行上面编码的查询,如果(('page' - 1)*'count')结果大于SELECT FOUND_ROWS();返回的值,则重新运行查询,将新LIMIT设置为0,计数。 这并不完美,因为传递的页面值很差的情况需要第二次数据库拉取,但鉴于这是一个意外情况,只是由用户有意传递坏数据触发,这是可以接受的。 如果其他人有更好的解决方案,我很乐意重新打开这个问题。 I ended up using the first solution above - Run the query ...
  • 首先,你需要想出一个清晰的界面。 每个模块需要具有相同的结构。 它是否是OOP并不重要,但它们都需要暴露相同的接口。 这是一个FFTG::Rename非-OOp实现示例。 我遗漏了很多东西,但我认为很清楚发生了什么。 package FFTG::Rename; use strict; use warnings; sub run { my ($args) = @_; if ($args->{mandatory}) { # do stuff here } ...
  • 将两个数组引用到@diagarray与你如何推动标量进入它并没有什么不同。 push(@diagarray,\@labels); push(@diagarray,\@values); 但是你希望这发生在while循环之外。 在while循环中,你可以填充@labels和@values。 两个阵列的大小必须相同。 此外,您的脚本试图一次性输出HTML和饼图,这将无法正常工作,因为您的浏览器只会将其视为一块HTML。 您的HTML需要在其中包含指向其他网址的“img”标记。 该URL可以是相同的脚本,但具有不 ...
  • 这完全属于如何处理子程序中的错误的问题。 对此进行了很好的讨论,但我现在找不到这些帖子。 原则上,这些是处理子例程中的错误的方法 返回码,其中一些表示错误 返回“特殊”值,如Perl中的undef 抛出异常,Perl中的设备就会die 调用者要么检查返回,要么测试undef ,或使用eval来捕获和处理die 。 什么是最合适的完全取决于上下文和代码的作用。 我认为在现代语言中没有太多理由限制指示错误的“代码”(如负值)。 首先,要么干涉合法的回报,要么限制它们通过指针/引用,这是一个重大的设计决定。 返回 ...
  • 您应该将文件名传递给get_record,如下所示: $text = &get_record(shift @ARGV); 在一个子程序中移动的参数传递给子程序(@_); 只有在子程序之外才能得到命令行参数。 You should be passing the filename to get_record, like: $text = &get_record(shift @ARGV); shift inside a subroutine gets arguments passed to the subro ...
  • 1.这种方法是否存在一些重大缺陷? my $_; 鉴于该块将隐藏您对包变量$_更改。 从mygrep里面你mygrep 。 &p;$code是非常特殊的。 您需要&$code()或$code->()来代替。 更改$_将改变传递给mygrep的参数。 这在这里是不可取的。 2.在设置$ _之前本地化$ _是一个更好的主意吗? for local提供了更好的本地化,但它也提供了在这里不受欢迎的别名。 3.我应该使用部分应用功能吗? 我不知道这意味着什么。 固定: sub mygrep (&@) { my ...
  • 一般规则是尽可能晚地声明每个变量。 如果一个变量的值不需要在一个循环的迭代中保留,那么在循环中声明它,或者作为for循环的循环控制变量。 如果它需要在循环迭代中保持静态(如$flag ),则在循环之前立即声明它。 是的,如果每次执行一个块时丢弃并重新分配一个变量,则需要支付最低的速度成本,但编程和维护成本是最重要的效率,应始终放在第一位。 在开始工作之前,您不应该优化您的代码,并且发现运行速度太慢; 即使如此,将声明移动到文件的顶部也是可能产生有益差异的妥协列表的很长一段路要走。 The general r ...
  • Perl在这种情况下神奇地处理标量,并且“假装”它通过引用传递它们。 有时它很有用,其他时候它是后方的痛苦。 Ah-ha在Perl编程第4章中找到了一个参考和解释: 如果LIST完全由可指定的值组成(意思是变量,通常不是枚举常量),则可以通过修改循环内的VAR来修改每个变量。 这是因为foreach循环索引变量是您正在循环的列表中每个项目的隐式别名。 感谢ysth从正式的perl文档中获得以下参考资料: 如果LIST的任何元素是左值,您可以通过修改循环内的VAR来修改它。 相反,如果LIST的任何元素不是左 ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。