import sys, os

def call_with_args(func, args):
    from datetime import datetime
    if '--profile' in args:
        args.remove('--profile')
        import cProfile
        now = datetime.now()
        cProfile.runctx('func(*args)', {}, dict(func=func, args=args),
                        '%s.profile' % func.__name__)
        print >>sys.stderr, "Profiled",func.__name__,"took",datetime.now()-now
        #from pstats import Stats
        #s = Stats('%s.profile' % func.__name__, stream=sys.stderr)
        #s.strip_dirs()
        #s.sort_stats('time')
        #s.sort_stats('cumulative')
        #s.print_stats()
        #s.print_callers()

        print >>sys.stderr, "gprof2dot to output.svg"
        # TODO(xavid): This is a dumb external dependency.
        os.system('/mit/xavid/bin/gprof2dot.py -f pstats %s.profile -n 1 --skew .05 | dot -Tsvg -o output.svg' % func.__name__)
        print >>sys.stderr, "Done."
    else:
        now = datetime.now()
        func(*args)
        print >>sys.stderr, func.__name__,"took",datetime.now()-now
