Skip to content
This repository has been archived by the owner on May 2, 2022. It is now read-only.

Commit

Permalink
move profile_func() from fwtwirl as print_profile_func()
Browse files Browse the repository at this point in the history
  • Loading branch information
TaiSakuma committed Feb 18, 2018
1 parent 406d858 commit 016ac93
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
1 change: 1 addition & 0 deletions alphatwirl/misc/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from .mkdir_p import mkdir_p
from .list_to_aligned_text import list_to_aligned_text
from .quote_string import quote_string
from .profile_func import profile_func, print_profile_func

# to be deleted
from .listToAlignedText import listToAlignedText
30 changes: 30 additions & 0 deletions alphatwirl/misc/profile_func.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Tai Sakuma <tai.sakuma@cern.ch>
from __future__ import print_function
import cProfile, pstats
from io import StringIO, BytesIO

##__________________________________________________________________||
def print_profile_func(func, profile_out_path=None):
result = profile_func(func)
if profile_out_path is None:
print(result)
else:
with open(profile_out_path, 'w') as f:
f.write(result)

##__________________________________________________________________||
def profile_func(func):
pr = cProfile.Profile()
pr.enable()
func()
pr.disable()
sortby = 'cumulative'
try:
s = StringIO()
pstats.Stats(pr, stream=s).strip_dirs().sort_stats(sortby).print_stats()
except TypeError:
s = BytesIO()
pstats.Stats(pr, stream=s).strip_dirs().sort_stats(sortby).print_stats()
return s.getvalue()

##__________________________________________________________________||
27 changes: 27 additions & 0 deletions tests/unit/misc/test_profile_func.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Tai Sakuma <tai.sakuma@gmail.com>
from __future__ import print_function
import os

import pytest

try:
import unittest.mock as mock
except ImportError:
import mock

from alphatwirl.misc import profile_func, print_profile_func

##__________________________________________________________________||
def test_profile_func():
func = mock.Mock()
profile_func(func)

##__________________________________________________________________||
def test_print_profile_func(tmpdir_factory):
tmpdir = str(tmpdir_factory.mktemp(''))
func = mock.Mock()
print(tmpdir)
profile_out_path = os.path.join(tmpdir, 'profile.txt')
print_profile_func(func, profile_out_path=profile_out_path)

##__________________________________________________________________||

0 comments on commit 016ac93

Please sign in to comment.