LoginSignup
3
1

More than 5 years have passed since last update.

pygameをUbuntu 16.04で使うと、CPU使用率が100%になる

Last updated at Posted at 2017-03-15

症状

Ubuntu 16.04でpygameを使うとCPU使用率が100%になります。

main.py
import time
import pygame

pygame.init()

while True:
    time.sleep(1)

何もしていないコードですが、topで確認すると

top
top - 13:18:43 up  6:21,  1 user,  load average: 0.78, 0.56, 0.48
Tasks: 329 total,   1 running, 328 sleeping,   0 stopped,   0 zombie
%Cpu(s): 26.0 us,  4.8 sy,  0.6 ni, 68.2 id,  0.4 wa,  0.0 hi,  0.0 si,  0.0 st
KiB Mem : 12222916 total,  5867808 free,  3502168 used,  2852940 buff/cache
KiB Swap: 12502012 total, 12502012 free,        0 used.  7608068 avail Mem 

  PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND     
18635 USER     20   0  704956  31568  18668 S  93.8  0.3   0:41.60 python2.7   
 1800 USER     20   0 1251136 113176  64712 S   6.2  0.9   6:27.81 compiz      
    1 root      20   0  119960   6064   3932 S   0.0  0.0   0:03.00 systemd     
    2 root      20   0       0      0      0 S   0.0  0.0   0:00.00 kthreadd    
    3 root      20   0       0      0      0 S   0.0  0.0   0:00.21 ksoftirqd/0 
    5 root       0 -20       0      0      0 S   0.0  0.0   0:00.00 kworker/0:+ 
    7 root      20   0       0      0      0 S   0.0  0.0   0:09.43 rcu_sched   
    8 root      20   0       0      0      0 S   0.0  0.0   0:00.00 rcu_bh      
    9 root      rt   0       0      0      0 S   0.0  0.0   0:00.09 migration/0 
   10 root      rt   0       0      0      0 S   0.0  0.0   0:00.04 watchdog/0  
   11 root      rt   0       0      0      0 S   0.0  0.0   0:00.04 watchdog/1  
   12 root      rt   0       0      0      0 S   0.0  0.0   0:00.07 migration/1 
   13 root      20   0       0      0      0 S   0.0  0.0   0:00.20 ksoftirqd/1 
   15 root       0 -20       0      0      0 S   0.0  0.0   0:00.00 kworker/1:+ 
   16 root      rt   0       0      0      0 S   0.0  0.0   0:00.04 watchdog/2  
   17 root      rt   0       0      0      0 S   0.0  0.0   0:00.08 migration/2 
   18 root      20   0       0      0      0 S   0.0  0.0   0:00.24 ksoftirqd/2 

となり、Pythonがえげつない時間CPUを専有していることがわかります。

環境は以下の通りです。
CPU:Core i3 4005u
Memory:12G
OS:Ubuntu 16.04(LTS)

調査・原因

どうもpygame.init()が悪さをしているようです。
pygameのドキュメントによると、pygame.init()は複数のモジュールを一括で初期化する関数のようです。
pygame.[モジュール名].init()で指定したモジュールのみを初期化できます。
というわけで、モジュールを個別に分けて初期化すると、pygame.base.init()を呼び出した直後にCPU使用率が100%になりました。これが原因かな?

対策

pygame.init()と書かずに、初期化が必要なモジュールがあればpygame.[モジュール名].init()で初期化するようにしました。幸いなことにpygame.baseは初期化しなくてもエラーにならないようなので、とりあえずはこれで解決しました。

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1