#!/usr/bin/env python3
# Thread profiler
# Copyright (C) 2014 Radek Hranicky
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


import cProfile
import pstats
import threading

class ThreadProfiler(object):
    
    """ Initialise a Thread Profiler
    Assumes a single string argument - a name of profiling
    """
    def __init__(self, profilingName):
        self.__profilingName = str(profilingName)
        self.__profile = cProfile.Profile()
        self.__threadName = str(threading.current_thread().getName())
    
    """
    Starts profiling of the thread
    """
    def begin(self):
        self.__profile.enable()
    
    """
    Stops profiling of the thread and save results to file named:
    profile_[PROFILINGNAME]_[THREADNAME].txt
    Where:
        [PROFILINGNAME] is the name of profiling set in the object constructor
        [THREADNAME] is the name of the current thread got by threading.current_thread().getName()
    """    
    def end(self):
        self.__profile.disable()
        fileName = 'profile_' + self.__profilingName + '_' + self.__threadName + '.txt'
        ofile = open(fileName, 'w');
        stats = pstats.Stats(self.__profile, stream=ofile)
        stats.strip_dirs().sort_stats("time").print_stats()
        ofile.close()
