Question: Consolidate time for each function. /* Function stage(start/ends) time(start/end) main start 0 <----------- main running foo start 3 foo end 7 <----------- main running zoo start 10 zoo end 13 <-------------- main running moo start 15 foo start 17 foo end 18 <---------------- moo running moo end 20 < --------------main running main end 22 Consolidate time for each function. */
Anonimo
import java.util.*; public class Main { //{pee=1, foo=5, main=10, zoo=3, moo=3} static Map calculateTimes(List input){ Map hm = new HashMap(); Stack stack =new Stack(); for(FuncObject funcObject:input){ if(funcObject.flag.equals("start")){ stack.push(funcObject); }else{ FuncObject poppedFunc = stack.pop(); poppedFunc.executionTime+=(funcObject.endTime-poppedFunc.startTime); poppedFunc.funcTime+=(funcObject.endTime-poppedFunc.startTime); int val = hm.getOrDefault(poppedFunc.functionName,0); hm.put(poppedFunc.functionName,val+poppedFunc.executionTime); if(!stack.isEmpty()){ FuncObject peekFunc = stack.peek(); peekFunc.executionTime += (-1*poppedFunc.funcTime); } } } return hm; } public static void main(String args[]){ String main = "main"; String foo = "foo"; String zoo = "zoo"; String moo = "moo"; String pee = "pee"; List input = new ArrayList(); input.add(new FuncObject(main, "start", 0)); input.add(new FuncObject(foo, "start", 3)); input.add(new FuncObject(foo, "end", 7)); input.add(new FuncObject(zoo, "start", 10)); input.add(new FuncObject(zoo, "end", 13)); input.add(new FuncObject(moo, "start", 15)); input.add(new FuncObject(foo, "start", 16)); input.add(new FuncObject(pee, "start", 17)); input.add(new FuncObject(pee, "end", 18)); input.add(new FuncObject(foo, "end", 18)); input.add(new FuncObject(moo, "end", 20)); input.add(new FuncObject(main, "end", 22)); Map res = calculateTimes(input); System.out.println("here" + res.toString()); } } class FuncObject{ int startTime; int endTime; int executionTime; int funcTime; String functionName; String flag; FuncObject(String fN,String flag,int time){ this.flag = flag; if(flag.equals("start")){ startTime = time; }else{ endTime = time; } functionName = fN; } }