| 1 |
# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE. |
| 2 |
# Copyright (C) NIWA & British Crown (Met Office) & Contributors. |
| 3 |
# |
| 4 |
# This program is free software: you can redistribute it and/or modify |
| 5 |
# it under the terms of the GNU General Public License as published by |
| 6 |
# the Free Software Foundation, either version 3 of the License, or |
| 7 |
# (at your option) any later version. |
| 8 |
# |
| 9 |
# This program is distributed in the hope that it will be useful, |
| 10 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 |
# GNU General Public License for more details. |
| 13 |
# |
| 14 |
# You should have received a copy of the GNU General Public License |
| 15 |
# along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 16 |
"""Cylc memory and performance profiling.""" |
| 17 |
|
| 18 |
import os |
| 19 |
import cProfile |
| 20 |
import io |
| 21 |
from pathlib import Path |
| 22 |
import pstats |
| 23 |
|
| 24 |
import psutil |
| 25 |
|
| 26 |
|
| 27 |
class Profiler: |
| 28 |
"""Wrap cProfile, pstats, and memory logging, for performance profiling.""" |
| 29 |
|
| 30 |
def __init__(self, schd, enabled=False): |
| 31 |
"""Initialize cProfile.""" |
| 32 |
self.schd = schd |
| 33 |
self.enabled = enabled |
| 34 |
if enabled: |
| 35 |
self.prof = cProfile.Profile() |
| 36 |
else: |
| 37 |
self.prof = None |
| 38 |
|
| 39 |
def start(self): |
| 40 |
"""Start profiling.""" |
| 41 |
if not self.enabled: |
| 42 |
return |
| 43 |
self.prof.enable() |
| 44 |
|
| 45 |
def stop(self): |
| 46 |
"""Stop profiling and print stats.""" |
| 47 |
if not self.enabled: |
| 48 |
return |
| 49 |
self.prof.disable() |
| 50 |
string_stream = io.StringIO() |
| 51 |
stats = pstats.Stats(self.prof, stream=string_stream) |
| 52 |
stats.sort_stats('cumulative') |
| 53 |
stats.print_stats() |
| 54 |
# dump to stdout |
| 55 |
print(string_stream.getvalue()) |
| 56 |
# write data file to workflow log dir |
| 57 |
if not self.schd: |
| 58 |
# if no scheduler present (e.g. validate) dump to PWD |
| 59 |
loc = Path() |
| 60 |
else: |
| 61 |
loc = Path(self.schd.workflow_log_dir) |
| 62 |
self.prof.dump_stats( |
| 63 |
Path(loc, 'profile.prof') |
| 64 |
) |
| 65 |
|
| 66 |
def log_memory(self, message): |
| 67 |
"""Print a message to standard out with the current memory usage.""" |
| 68 |
if not self.enabled: |
| 69 |
return |
| 70 |
memory = psutil.Process(os.getpid()).memory_info().rss / 1024 |
| 71 |
print("PROFILE: Memory: %d KiB: %s" % (memory, message)) |