#!/usr/bin/env python
# __BEGIN_LICENSE__
#  Copyright (c) 2009-2013, United States Government as represented by the
#  Administrator of the National Aeronautics and Space Administration. All
#  rights reserved.
#
#  The NGT platform is licensed under the Apache License, Version 2.0 (the
#  "License"); you may not use this file except in compliance with the
#  License. You may obtain a copy of the License at
#  http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
# __END_LICENSE__

from __future__ import print_function
import os, sys, optparse, string, subprocess, math

from asp_system_utils import get_asp_version

import asp_system_utils
asp_system_utils.verify_python_version_is_supported()

def convert_to_seconds( time ):
    time = time.strip()
    return float(time[:time.find("m")]) * 60.0 + float(time[time.find("m")+1:-1])

def main():
    try:
        usage = "usage: time_trials [options] command\n  " + get_asp_version()
        parser = optparse.OptionParser(usage=usage)
        parser.set_defaults(trials=5)
        parser.add_option("--trials", dest="trials",
                          help="Number of trials to run.", type="int")

        (options, args) = parser.parse_args()

        if not args: raise Exception('No input command')

    except optparse.OptionError as msg:
        print(msg, file=sys.stderr)
        return 2

    print("Running command: [%s]" % args[0])

    real_mean   = 0.0
    real_stddev = 0.0
    user_mean   = 0.0
    user_stddev = 0.0
    sys_mean    = 0.0
    sys_stddev  = 0.0

    for i in range(0,options.trials):
        print(" -> trial %i / %i " % (i+1,options.trials))
        p = subprocess.Popen("( time %s ) 2>&1 | tail -n3 "%args[0] , shell=True, stdout=subprocess.PIPE, universal_newlines=True)
        output    = p.stdout.read().strip().split()
        real_time = convert_to_seconds( output[1] )
        user_time = convert_to_seconds( output[3] )
        sys_time  = convert_to_seconds( output[5] )
        print("r%.1f, u%.1f, s%.1f" % (real_time, user_time, sys_time))

        # Accumulate values
        real_mean   += real_time / float(options.trials)
        real_stddev += real_time * real_time  / float(options.trials)
        user_mean   += user_time / float(options.trials)
        user_stddev += user_time * user_time  / float(options.trials)
        sys_mean    += sys_time / float(options.trials)
        sys_stddev  += sys_time * sys_time  / float(options.trials)


    real_stddev = real_stddev - real_mean*real_mean
    real_stddev = math.sqrt(real_stddev)
    user_stddev = user_stddev - user_mean*user_mean
    user_stddev = math.sqrt(user_stddev)
    sys_stddev  = sys_stddev - sys_mean*sys_mean
    sys_stddev  = math.sqrt(sys_stddev)

    print("Real:   %.3f +- %.3f" % (real_mean, real_stddev))
    print("User:   %.3f +- %.3f" % (user_mean, user_stddev))
    print("Sys:    %.3f +- %.3f" % (sys_mean,  sys_stddev ))

if __name__ == "__main__":
    sys.exit(main())
