|
| 1 | +# Copyright 2016 Google Inc. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""A profiler context manager based on cProfile.Profile objects.""" |
| 16 | + |
| 17 | +import cProfile |
| 18 | +import logging |
| 19 | +import os |
| 20 | +import pstats |
| 21 | +import StringIO |
| 22 | +import tempfile |
| 23 | +import time |
| 24 | + |
| 25 | + |
| 26 | +from google.cloud.dataflow.utils.dependency import _dependency_file_copy |
| 27 | + |
| 28 | + |
| 29 | +class Profile(object): |
| 30 | + """cProfile wrapper context for saving and logging profiler results.""" |
| 31 | + |
| 32 | + SORTBY = 'cumulative' |
| 33 | + |
| 34 | + def __init__(self, profile_id, profile_location=None, log_results=False): |
| 35 | + self.stats = None |
| 36 | + self.profile_id = str(profile_id) |
| 37 | + self.profile_location = profile_location |
| 38 | + self.log_results = log_results |
| 39 | + |
| 40 | + def __enter__(self): |
| 41 | + logging.info('Start profiling: %s', self.profile_id) |
| 42 | + self.profile = cProfile.Profile() |
| 43 | + self.profile.enable() |
| 44 | + return self |
| 45 | + |
| 46 | + def __exit__(self, *args): |
| 47 | + self.profile.disable() |
| 48 | + logging.info('Stop profiling: %s', self.profile_id) |
| 49 | + |
| 50 | + if self.profile_location: |
| 51 | + dump_location = os.path.join( |
| 52 | + self.profile_location, 'profile', |
| 53 | + ('%s-%s' % (time.strftime('%Y-%m-%d_%H_%M_%S'), self.profile_id))) |
| 54 | + fd, filename = tempfile.mkstemp() |
| 55 | + self.profile.dump_stats(filename) |
| 56 | + logging.info('Copying profiler data to: [%s]', dump_location) |
| 57 | + _dependency_file_copy(filename, dump_location) # pylint: disable=protected-access |
| 58 | + os.close(fd) |
| 59 | + os.remove(filename) |
| 60 | + |
| 61 | + if self.log_results: |
| 62 | + s = StringIO.StringIO() |
| 63 | + self.stats = pstats.Stats( |
| 64 | + self.profile, stream=s).sort_stats(Profile.SORTBY) |
| 65 | + self.stats.print_stats() |
| 66 | + logging.info('Profiler data: [%s]', s.getvalue()) |
0 commit comments