import json
import inspect

from datetime import datetime
from functools import wraps


def profiled(f):
  """
  A decorator that records and prints the time taken for the decorated function to complete

  TODO: improve this (but this rudimentary format has proven useful for development)
  """

  calling_module = inspect.getmodule(inspect.currentframe().f_back)
  calling_module_name = calling_module and calling_module.__name__ or None
  @wraps(f)
  def run(*args, **kwargs):
    start = datetime.now()
    try:
      return f(*args, **kwargs)
    finally:
      end = datetime.now()
      print("[@profiled] " + json.dumps([calling_module_name, f.__name__, (end - start).total_seconds()]))
  return run
