#!/usr/bin/env python

# Copyright (C) 2010 Anders Logg
#
# This file is part of DOLFIN.
#
# DOLFIN is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# DOLFIN 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with DOLFIN. If not, see <http://www.gnu.org/licenses/>.
#
# Modified by Garth N. Wells, 2011.
# Modified by Johannes Ring, 2011.
#
# First added:  2010-05-03
# Last changed: 2011-04-05

import commands

# Parameters for benchmark
SIZE = 64
NUM_PROCS = 4

print "Assembly/solve speedup running on %s processors" % NUM_PROCS

# Function for extracting test name and time from benchmark
def get_time(output):
    lines = [line for line in output.split("\n") if "TIME" in line]
    timing = []
    for line in lines:
        time = float(line.split(":")[-1])
        name = line.split(":")[-2].strip("TIME").strip(None).replace("(", "").replace(")", "")
        timing.append( (name, time) )
    return timing

# Serial assembly
output = commands.getoutput("./assemble-poisson %d" % SIZE)
assembly_t1 = get_time(output)
print "Serial assembly:", assembly_t1

# Parallel assembly
output = commands.getoutput("mpirun -n %d ./assemble-poisson %d" % (NUM_PROCS, SIZE))
assembly_t2 = get_time(output)
print "Parallel assembly:", assembly_t2

# Serial solve
output = commands.getoutput("./solve-poisson %d" % SIZE)
solve_t1 = get_time(output)
print "Serial solve:", solve_t1

# Parallel solve
output = commands.getoutput("mpirun -n %d ./solve-poisson %d" % (NUM_PROCS, SIZE))
solve_t2 = get_time(output)
print "Parallel solve:", solve_t2

print "assembly"
for test1, test2  in zip(assembly_t1, assembly_t2):
    print "  ", test1[0] + ":", test1[1]/test2[1]

print "solve"
for test1, test2  in zip(solve_t1, solve_t2):
    print "  ", test1[0] + ":", test1[1]/test2[1]

print "BENCH assembly", assembly_t1[0][1] / assembly_t2[0][1] + assembly_t1[1][1] / assembly_t2[1][1]
print "BENCH solve", solve_t1[0][1] / solve_t2[0][1]
