Portable way of detecting number of *usable* CPUs in Python

前端 未结 2 1277
执笔经年
执笔经年 2021-02-05 02:26

Per this question and answer -- Python multiprocessing.cpu_count() returns '1' on 4-core Nvidia Jetson TK1 -- the output of Python\'s multiprocessing.cpu_count()<

相关标签:
2条回答
  • 2021-02-05 03:19

    I don't think you will get any truly portable answers, so I will give a correct one.

    The correct* answer for Linux is len(os.sched_getaffinity(pid)), where pid may be 0 for the current process. This function is exposed in Python 3.3 and later; if you need it in earlier, you'll have to do some fancy cffi coding.

    Edit: you might try to see if you can use a function int omp_get_num_procs(); if it exists, it is the only meaningful answer I found on this question but I haven't tried it from Python.

    0 讨论(0)
  • 2021-02-05 03:24

    Use psutil:

    from the doc https://psutil.readthedocs.io/en/latest/:

    >>> import psutil
    >>> psutil.cpu_count()
    4
    >>> psutil.cpu_count(logical=False)  # Ignoring virtual cores
    2
    

    This is portable

    0 讨论(0)
提交回复
热议问题