List of usage examples for com.google.common.base Stopwatch Stopwatch
Stopwatch()
From source file:org.caleydo.view.tourguide.impl.PAGEAlgorithm.java
@Override public void init(IProgressMonitor monitor) { if (!foldChanges.isEmpty()) return;// w ww. j a v a2 s .co m final Set<Integer> inA = new HashSet<>(perspective.getVirtualArray().getIDsOfGroup(group.getGroupIndex())); ATableBasedDataDomain dataDomain = (ATableBasedDataDomain) perspective.getDataDomain(); Table table = dataDomain.getTable(); List<Integer> rows = perspective.getVirtualArray().getIDs(); List<Integer> cols = table.getDefaultDimensionPerspective(false).getVirtualArray().getIDs(); Stopwatch w = new Stopwatch().start(); float sum = 0; float squaredSum = 0; for (Integer col : cols) { // mean of the expressions level of the samples for the given gen. float asum = 0; int acount = 0; float bsum = 0; int bcount = 0; for (Integer row : rows) { Float v = table.getRaw(col, row); if (v == null || v.isNaN() || v.isInfinite()) continue; if (inA.contains(row)) { asum += v; acount++; } else { bsum += v; bcount++; } } if (monitor.isCanceled()) { foldChanges.clear(); // undo init return; } // now some kind of correlation between the two float foldChange = Statistics.foldChange((asum / acount), (bsum / bcount)); Set<Integer> davids = dim2primary.apply(col); if (davids == null) continue; sum += foldChange * davids.size(); squaredSum += (foldChange * foldChange) * davids.size(); for (Integer david : davids) foldChanges.put(david, foldChange); } foldChangesMean = sum / foldChanges.size(); foldChangesSD = (float) Math.sqrt(squaredSum / foldChanges.size() - foldChangesMean * foldChangesMean); System.out.println(w); }
From source file:org.apache.drill.exec.expr.fn.FunctionImplementationRegistry.java
public FunctionImplementationRegistry(DrillConfig config) { Stopwatch w = new Stopwatch().start(); logger.debug("Generating function registry."); drillFuncRegistry = new DrillFunctionRegistry(config); Set<Class<? extends PluggableFunctionRegistry>> registryClasses = PathScanner.scanForImplementations( PluggableFunctionRegistry.class, config.getStringList(ExecConstants.FUNCTION_PACKAGES)); for (Class<? extends PluggableFunctionRegistry> clazz : registryClasses) { for (Constructor<?> c : clazz.getConstructors()) { Class<?>[] params = c.getParameterTypes(); if (params.length != 1 || params[0] != DrillConfig.class) { logger.warn(/*from ww w.ja v a 2s.c o m*/ "Skipping PluggableFunctionRegistry constructor {} for class {} since it doesn't implement a " + "[constructor(DrillConfig)]", c, clazz); continue; } try { PluggableFunctionRegistry registry = (PluggableFunctionRegistry) c.newInstance(config); pluggableFuncRegistries.add(registry); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { logger.warn("Unable to instantiate PluggableFunctionRegistry class '{}'. Skipping it.", clazz, e); } break; } } logger.info("Function registry loaded. {} functions loaded in {} ms.", drillFuncRegistry.size(), w.elapsed(TimeUnit.MILLISECONDS)); }
From source file:org.arbeitspferde.friesian.WorkEngine.java
public void run() { long startMillis; init();/*from w w w .j a v a 2 s . c o m*/ while (workNotFinished()) { // TODO(mtp): This introduces non-determinism for testing; fix. final Stopwatch timer = new Stopwatch().start(); doWork(); timer.stop(); jtaWorkerWorkTime.addAndGet(timer.elapsed(TimeUnit.MILLISECONDS)); if (sleepProbability >= RandomNumber.generatePercentage(rng)) { try { Thread.sleep(workerSleepTime); jtaWorkerSleepTime.addAndGet(workerSleepTime); } catch (InterruptedException e) { log.log(Level.WARNING, "Worker is unable to sleep", e); } } } cache(); }
From source file:eugene.simulation.agent.impl.StartSimulationBehaviour.java
@Override public void onStart() { try {/*from w ww. j a v a2s .c o m*/ final Stopwatch stopwatch = new Stopwatch().start(); final Calendar startCalendar = getInstance(); final Calendar stopCalendar = (Calendar) startCalendar.clone(); stopCalendar.add(Calendar.MILLISECOND, length); final Action action = new Action(myAgent.getAID(), new Start(startCalendar.getTime(), stopCalendar.getTime())); final ACLMessage aclMessage = new ACLMessage(ACLMessage.REQUEST); aclMessage.setLanguage(SimulationOntology.LANGUAGE); aclMessage.setOntology(SimulationOntology.NAME); myAgent.getContentManager().fillContent(aclMessage, action); final AchieveREInitiator sender = new AchieveREInitiator(myAgent, aclMessage) { @Override protected Vector prepareRequests(final ACLMessage request) { final Vector l = new Vector(guids.getObject().size()); final ACLMessage clone = (ACLMessage) request.clone(); for (final String guid : guids.getObject()) { clone.addReceiver(new AID(guid, AID.ISGUID)); } l.addElement(clone); return l; } @Override public void handleAllResultNotifications(Vector responses) { try { if (guids.getObject().size() != responses.size()) { result.fail(); return; } for (final Object o : responses) { if (!(o instanceof ACLMessage)) { result.fail(); } final ContentElement ce = myAgent.getContentManager().extractContent((ACLMessage) o); if (!(ce instanceof Action) || null == ((Action) ce).getAction() || !(((Action) ce).getAction() instanceof Started)) { result.fail(); } if (!guids.getObject().contains(((ACLMessage) o).getSender().getName())) { result.fail(); } } LOG.info("Sending Start messages took {}", stopwatch.stop()); result.success(startCalendar); } catch (CodecException e) { LOG.error(ERROR_MSG, e); result.fail(); } catch (OntologyException e) { LOG.error(ERROR_MSG, e); result.fail(); } } }; addSubBehaviour(sender); } catch (CodecException e) { LOG.error(ERROR_MSG, e); result.fail(); } catch (OntologyException e) { LOG.error(ERROR_MSG, e); result.fail(); } }
From source file:com.google.appengine.tools.cloudstorage.RetryHelper.java
private RetryHelper(Body<V> body, RetryParams parms) { this(body, parms, new Stopwatch()); }
From source file:com.github.zhongl.api.Storage.java
public void merge(Collection<WriteOperation<Entry<Key, V>>> addOrUpdates, Collection<WriteOperation<Key>> removes, FutureCallback<Void> flushedCallback) { Stopwatch stopwatch = new Stopwatch().start(); try {//from w w w .j a v a 2 s .com if (defragPolicy.evaluate(snapshot.aliveSize(), addOrUpdates.size() - removes.size())) { defrag(addOrUpdates, removes); lastBehavior = Behavior.DEFRAG; } else { append(addOrUpdates, removes); lastBehavior = Behavior.APPEND; } onSuccess(addOrUpdates); onSuccess(removes); snapshot.updateAndCleanUp(); } catch (OutOfMemoryError e) { logger.log(Level.WARNING, "Reject add or update operations because ", e); onFailure(addOrUpdates, e); if (!addOrUpdates.isEmpty() // avoid recursion merging over 2 level && !removes.isEmpty()) merge(Collections.<WriteOperation<Entry<Key, V>>>emptySet(), removes, flushedCallback); } catch (Throwable e) { logger.log(Level.WARNING, "Merge failed because ", e); onFailure(addOrUpdates, e); onFailure(removes, e); lastBehavior = Behavior.FAIL; } finally { flushedCallback.onSuccess(Nils.VOID); lastBehaviorElapseMillis = stopwatch.stop().elapsedMillis(); } }
From source file:org.apache.hadoop.yarn.server.applicationhistoryservice.metrics.loadsimulator.net.RestMetricsSender.java
/** * Push metrics to the REST endpoint. Connection is always open and closed on every call. * * @param payload the payload with metrics to be sent to metrics service * @return response message either acknowledgement or error, empty on exception *//*from www . j a v a2s .c o m*/ @Override public String pushMetrics(String payload) { String responseString = ""; UrlService svc = null; Stopwatch timer = new Stopwatch().start(); try { LOG.info("server: {}", collectorServiceAddress); svc = getConnectedUrlService(); responseString = svc.send(payload); timer.stop(); LOG.info("http response time: " + timer.elapsedMillis() + " ms"); if (responseString.length() > 0) { LOG.debug("POST response from server: " + responseString); } } catch (MalformedURLException e) { LOG.error("", e); } catch (ProtocolException e) { LOG.error("", e); } catch (IOException e) { LOG.error("", e); } finally { if (svc != null) { svc.disconnect(); } } return responseString; }
From source file:org.caleydo.view.tourguide.internal.compute.ComputeStratificationJob.java
@Override public IStatus run(IProgressMonitor monitor) { if (data.isEmpty() || (stratScores.isEmpty() && stratMetrics.isEmpty())) return Status.OK_STATUS; final int total = data.size() + 1; monitor.beginTask("Compute LineUp Scores", total); log.info("computing similarity of %d against %d stratification scores, %d stratification metrics", data.size(), stratScores.size(), stratMetrics.size()); Stopwatch w = new Stopwatch().start(); // first initialize all algorithms progress(0, "Initializing..."); for (IComputedStratificationScore score : Iterables.concat(stratMetrics, stratScores)) { score.getAlgorithm().init(monitor); if (Thread.interrupted() || monitor.isCanceled()) return Status.CANCEL_STATUS; }/*from ww w . jav a 2s . co m*/ int c = 0; monitor.worked(1); progress(c++ / (float) total, "Computing..."); Iterator<IComputeElement> it = this.data.iterator(); // first time the one run to compute the progress frequency interval { IComputeElement as = it.next(); if (!run(monitor, as)) return Status.CANCEL_STATUS; monitor.worked(1); c++; } final int fireEvery = fireEvery(w.elapsedMillis()); int f = fireEvery - 1; while (it.hasNext()) { IComputeElement as = it.next(); if (f == 0) { progress(c / (float) total, "Computing " + as.getLabel()); f = fireEvery; } f--; if (!run(monitor, as)) return Status.CANCEL_STATUS; monitor.worked(1); c++; } System.out.println("done in " + w); monitor.done(); return Status.OK_STATUS; }
From source file:org.apache.drill.jdbc.test.JdbcTestActionBase.java
protected void testAction(JdbcAction action, long rowcount) throws Exception { int rows = 0; Stopwatch watch = new Stopwatch().start(); ResultSet r = action.getResult(connection); boolean first = true; while (r.next()) { rows++;/*from www. ja v a 2s . c o m*/ ResultSetMetaData md = r.getMetaData(); if (first == true) { for (int i = 1; i <= md.getColumnCount(); i++) { System.out.print(md.getColumnName(i)); System.out.print('\t'); } System.out.println(); first = false; } for (int i = 1; i <= md.getColumnCount(); i++) { System.out.print(r.getObject(i)); System.out.print('\t'); } System.out.println(); } System.out.println(String.format("Query completed in %d millis.", watch.elapsed(TimeUnit.MILLISECONDS))); if (rowcount != -1) { Assert.assertEquals((long) rowcount, (long) rows); } System.out.println("\n\n\n"); }
From source file:de.blizzy.documentr.access.BCryptPasswordEncoder.java
@Override public boolean isPasswordValid(String encPass, String rawPass, Object salt) { Stopwatch stopwatch = new Stopwatch(); stopwatch.start();/* w w w . ja v a 2 s . c o m*/ boolean valid = encoder.matches(rawPass, encPass); stopwatch.stop(); if (log.isTraceEnabled()) { log.trace("time taken to verify password: {} ms", stopwatch.elapsedMillis()); //$NON-NLS-1$ } return valid; }