【发布时间】:2019-11-28 22:03:25
【问题描述】:
我是 python 新手,我正在尝试使用 pool.map() 加载 CPU。以下代码在不包含在类中时会在 CPU 上进行加载
def f(x):
while True:
x*x
def load(cores):
print('utilizing %d cores' % (cores/2))
pool = Pool(10)
pool.map(f, range(6))
但是,当我把它放在一个类中并尝试运行代码时
class test_cpu:
def f(x):
while True:
x*x
def load(cores):
print('utilizing %d cores' % (cores/2))
pool = Pool(10)
pool.map(f, range(6))
if __name__ == '__main__':
print('There are %d CPUs in your PC' % multiprocessing.cpu_count())
cores_count = multiprocessing.cpu_count()
input_user = input('What do you want to tes? type CPU, Memory or Both: ')
input_user.lower()
if input_user == 'cpu':
test_cpu.load(cores_count)
当我输入 CPU 时,它会打印此错误,说明函数 f 未定义
utilizing 4 cores
Traceback (most recent call last):
File "test_all.txt", line 81, in <module>
test_cpu.load(cores_count)
File "test_all.txt", line 45, in load
pool.map(f, range(6))
NameError: name 'f' is not defined
我应该怎么做才能解决这个问题?
【问题讨论】:
-
请用无效的代码更新您的问题。
-
您应该显示不起作用的代码。问题显然与
when I put it in a class有关,但你没有表现出来,所以我们只能猜测是什么问题? -
欢迎来到 SO - 请提供minimal reproducible example。
-
如果
f成为一种方法,您需要将其称为self.f。
标签: python dictionary pool