简体   繁体   English

Python时间分析每个语句作为参数的函数

[英]Python time profiling each statement as a function of parameters

I want to time profile python code as a function of 2 parameters. 我想将python代码配置为2个参数的函数。 For example, 例如,

param1 = 1
param2 = 2

# code goes here
# stmt 1
# stmt 2
# ...
# end

I want to plot time as a function of parameters for each statement in the code. 我想将时间绘制为代码中每个语句的参数函数。 I can think of a brute force approach for maintaining a database to store these values. 我可以想到一种蛮力维护数据库来存储这些值的方法。 Are there mature python libraries that do this automatically? 是否有成熟的python库可以自动执行此操作?

I ended up creating 2 classes to serve my purpose: 我最终创建了两个类来实现我的目的:

import time
class Timer(object):
  def __init__(self, times = None):
    """ times is a dictionary of key:int or list
     """
    self.times = times

  def start(self, key):
    if type(self.times[key]) == list:
        self.times[key].append(time.time())
    else:
        self.times[key] = time.time()

  def stop(self, key):
    if type(self.times[key]) == list:
        self.times[key][-1] = time.time() - self.times[key][-1]
    else:
        self.times[key] = time.time() - self.times[key]

from collections import defaultdict
class TimeProfiler(object):
  def __init__(self, msg):
    """ msg is to distinguish between different profilers"""
    self.msg = msg
    self.times = defaultdict(list)

  def append(self, attr, timer):
    self.times['ATTR'].append(attr)
    for key, value in timer.times.iteritems():
        self.times[key].append(value)

  def plot(self, key):
    if type(self.times[key][0]) == list:
        y = [x[0] for x in self.times[key]]
    else:
        y = self.times[key]
    # use your favorite potting library

  def make_key(self, final_key, base_keys= []):
    # combine several keys
    self.times[final_key] = [sum(i) for i in zip((self.times[x] for x in base_keys))]

To use the above two: 要使用以上两个:

 time_profiler = TimeProfiler("experiment1")
 for attr in range(10):
   timer = Timer({'stmt1':0, 'stmt2':0})
   timer.start('stmt1');
   #stmt1
   timer.stop('stmt1'); timer.start('stmt2');
   #stmt2
   timer.stop('stmt2');
   time_profiler.append(attr, timer)

 time_profiler.plot(1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM