/** * Time a multi-threaded access to a cache. * * @return the timing stopwatch */ private <V> StopWatch timeMultiThreaded( String id, final Map<Integer, V> map, ValueFactory<V> factory) throws InterruptedException { StopWatch stopWatch = new StopWatch(id); for (int i = 0; i < 500; i++) { map.put(i, factory.newValue(i)); } Thread[] threads = new Thread[30]; stopWatch.start("Running threads"); for (int threadIndex = 0; threadIndex < threads.length; threadIndex++) { threads[threadIndex] = new Thread("Cache access thread " + threadIndex) { @Override public void run() { for (int j = 0; j < 1000; j++) { for (int i = 0; i < 1000; i++) { map.get(i); } } } }; } for (Thread thread : threads) { thread.start(); } for (Thread thread : threads) { if (thread.isAlive()) { thread.join(2000); } } stopWatch.stop(); return stopWatch; }
// sample usage public static void main(String[] args) { StopWatch s = new StopWatch(); s.start(); // code you want to time goes here s.stop(); System.out.println("elapsed time in milliseconds: " + s.getElapsedTime()); }
@Test(dataProvider = "composeAllPermutationsOfSamInputResource") public void queryInputResourcePermutation(final SamInputResource resource) throws IOException { final SamReader reader = SamReaderFactory.makeDefault().open(resource); LOG.info(String.format("Query from %s ...", resource)); if (reader.hasIndex()) { final StopWatch stopWatch = new StopWatch(); stopWatch.start(); final SAMRecordIterator q1 = reader.query("chr1", 500000, 100000000, true); observedRecordOrdering1.add(Iterables.slurp(q1)); q1.close(); final SAMRecordIterator q20 = reader.query("chr20", 1, 1000000, true); observedRecordOrdering20.add(Iterables.slurp(q20)); q20.close(); final SAMRecordIterator q3 = reader.query("chr3", 1, 10000000, true); observedRecordOrdering3.add(Iterables.slurp(q3)); q3.close(); stopWatch.stop(); LOG.info(String.format("Finished queries in %sms", stopWatch.getElapsedTime())); Assert.assertEquals( observedRecordOrdering1.size(), 1, "read different records for chromosome 1"); Assert.assertEquals( observedRecordOrdering20.size(), 1, "read different records for chromosome 20"); Assert.assertEquals( observedRecordOrdering3.size(), 1, "read different records for chromosome 3"); } else if (resource.indexMaybe() != null) { LOG.warn("Resource has an index source, but is not indexed: " + resource); } else { LOG.info("Skipping query operation: no index."); } reader.close(); }
public static void main(String[] args) { StopWatch stopWatch1 = new StopWatch(); final int LENGTH_OF_LIST = 100000; int[] list = new int[LENGTH_OF_LIST]; stopWatch1.start(); for (int i = 0; i < LENGTH_OF_LIST; i++) { list[i] = (int) (Math.random() * list.length); } for (int i = 0; i < LENGTH_OF_LIST; i++) { int currentMin = list[i]; int currentMinIndex = i; for (int j = i + 1; j < LENGTH_OF_LIST; j++) { if (currentMin > list[j]) { currentMin = list[j]; currentMinIndex = j; } } if (currentMinIndex != i) { list[currentMinIndex] = list[i]; list[i] = currentMin; } } stopWatch1.stop(); System.out.println( "The execution time of sorting 10000 numbers using selection sort is " + stopWatch1.getElapsedTime()); }
/** Finds shortcuts, does not change the underlying graph. */ void findShortcuts(ShortcutHandler sch) { long tmpDegreeCounter = 0; EdgeIterator incomingEdges = vehicleInExplorer.setBaseNode(sch.getNode()); // collect outgoing nodes (goal-nodes) only once while (incomingEdges.next()) { int u_fromNode = incomingEdges.getAdjNode(); // accept only uncontracted nodes if (g.getLevel(u_fromNode) != 0) continue; double v_u_weight = incomingEdges.getDistance(); int skippedEdge1 = incomingEdges.getEdge(); int incomingEdgeOrigCount = getOrigEdgeCount(skippedEdge1); // collect outgoing nodes (goal-nodes) only once EdgeIterator outgoingEdges = vehicleOutExplorer.setBaseNode(sch.getNode()); // force fresh maps etc as this cannot be determined by from node alone (e.g. same from node // but different avoidNode) algo.clear(); tmpDegreeCounter++; while (outgoingEdges.next()) { int w_toNode = outgoingEdges.getAdjNode(); // add only uncontracted nodes if (g.getLevel(w_toNode) != 0 || u_fromNode == w_toNode) { continue; } // Limit weight as ferries or forbidden edges can increase local search too much. // If we decrease the correct weight we only explore less and introduce more shortcuts. // I.e. no change to accuracy is made. double existingDirectWeight = v_u_weight + outgoingEdges.getDistance(); algo.setLimitWeight(existingDirectWeight) .setLimitVisitedNodes((int) meanDegree * 100) .setEdgeFilter(levelEdgeFilter.setAvoidNode(sch.getNode())); dijkstraSW.start(); dijkstraCount++; int endNode = algo.findEndNode(u_fromNode, w_toNode); dijkstraSW.stop(); // compare end node as the limit could force dijkstra to finish earlier if (endNode == w_toNode && algo.getWeight(endNode) <= existingDirectWeight) // FOUND witness path, so do not add shortcut continue; sch.foundShortcut( u_fromNode, w_toNode, existingDirectWeight, outgoingEdges, skippedEdge1, incomingEdgeOrigCount); } } if (sch instanceof AddShortcutHandler) { // sliding mean value when using "*2" => slower changes meanDegree = (meanDegree * 2 + tmpDegreeCounter) / 3; // meanDegree = (meanDegree + tmpDegreeCounter) / 2; } }
private Set<List<Integer>> distributions(int bound, List<GrammarProductionElement> elems) { distroTimer.start(); int sumSize = elems.size(); List<Integer> lowerBounds = lowerBounds(elems, bound); List<Integer> upperBounds = upperBounds(elems, bound, lowerBounds); Set<List<Integer>> result = distributor.distribute2(sumSize, bound, lowerBounds, upperBounds); distroTimer.stop(); return result; }
public static void main(String[] args) { int[] array = ArrayUtils.randomIntArray(10000, 100); System.out.println(Arrays.toString(array)); StopWatch stopwatch = new StopWatch(); stopwatch.start(); System.out.println( Arrays.toString(DuplicateRemover.removeDuplicates(Arrays.copyOf(array, array.length)))); stopwatch.stop(); stopwatch.showElapsedTime(); stopwatch.reset(); stopwatch.start(); System.out.println( Arrays.toString(DuplicateRemover.removeDuplicatesBest(Arrays.copyOf(array, array.length)))); stopwatch.stop(); stopwatch.showElapsedTime(); stopwatch.reset(); }
/** * Stress Test of selectionRectangleChanged method.<br> * Print the time interval for recording. */ public void testSelectionRectangleChanged() { StopWatch watch = new StopWatch(); watch.start(); for (int i = 0; i < StressHelper.TEST_LOOP_COUNT; i++) { handler.selectionRectangleChanged(event); } System.out.println( String.format( "Running SelectionHandler#selectionRectangleChanged() method for" + " %d times consumes %d milliseconds.", StressHelper.TEST_LOOP_COUNT, watch.stop())); }
@Override public PrepareContractionHierarchies doWork() { checkGraph(); if (prepareEncoder == null) throw new IllegalStateException("No vehicle encoder set."); if (prepareWeighting == null) throw new IllegalStateException("No weight calculation set."); allSW.start(); super.doWork(); initFromGraph(); if (!prepareEdges()) return this; if (!prepareNodes()) return this; contractNodes(); return this; }
/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); this.deviceInfo = getDeviceInfoFromApplicationContext(); StopWatch sw = new StopWatch(); sw.start("create activity"); createAnimation(); buildFadeInPageViewAnimation(); buildFadeOutPageViewAnimation(); setProgressBarIndeterminateVisibility(false); System.out.println("debug on create"); executor = new ThreadPoolExecutor( 0, Integer.MAX_VALUE, 10L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); sourceDB = new SourceDB(this); alarmSender = new AlarmSender(this); // sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE); // acceleromererSensor = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); // createShakeListener(); Cursor sourceCursor = sourceDB.findAll(); startManagingCursor(sourceCursor); sourceAdapter = new SourceItemArrayAdapter<SourceItem>(this, R.layout.source_item, sourceDB, deviceInfo); TelephonyManager tManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE); deviceId = tManager.getDeviceId(); inflater = LayoutInflater.from(this); accountType = (String) getIntent().getExtras().get("type"); sourceId = (String) getIntent().getExtras().get("sourceId"); sourceImageURL = (String) getIntent().getExtras().get("sourceImage"); sourceName = (String) getIntent().getExtras().get("sourceName"); contentUrl = (String) getIntent().getExtras().get("contentUrl"); //// System.out.println("sourceImageURL:" + sourceImageURL); setContentView(R.layout.main); container = (ViewGroup) findViewById(R.id.pageContainer); pageIndexView = (PageIndexView) findViewById(R.id.pageIndex); ViewSwitcher headerSwitcher = (ViewSwitcher) findViewById(R.id.flipper); header = (HeaderView) findViewById(R.id.header); contentImageButton = (ImageButton) findViewById(R.id.content); contentImageButton.setOnClickListener( new View.OnClickListener() { public void onClick(View view) { overridePendingTransition(android.R.anim.slide_in_left, R.anim.fade); PageActivity.this.finish(); } }); // pageInfo = (TextView)header.findViewById(R.id.pageInfo); headerText = (TextView) findViewById(R.id.headerText); headerImageView = (WebImageView) findViewById(R.id.headerImage); pageViewFactory = new WeiboPageViewFactory(); preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); this.browseMode = getBrowseMode(); // this.animationMode = getAnimationMode(); refreshingSemaphore = new Semaphore(1, true); Log.v("accountType", accountType); reload(); }
public void run() { StopWatch st = null; if (GPResourceHome.perfProfile.PROFILE) { st = new StopWatch(false, false, true); st.start(); } StopWatch ct = new StopWatch(); int numWorkers = 0; try { if (GPResourceHome.commonState == null) { GPResourceHome.load_common(); } } catch (Exception e) { e.printStackTrace(); } ct.start(); while (true) { if (GPResourceHome.perfProfile.PROFILE) { st.stop(); GPResourceHome.perfProfile.addSample("notification_engine_worker", st.getElapsedTimeMX()); st.reset(); st.start(); } GPResource gpResource = null; try { // logger.debug("gpResource.notificationWorkerQ.remove()..."); gpResource = (GPResource) GPResourceHome.commonState.getNextResource(); // gpResource = // (GPResource)GPResourceHome.commonState.notificationWorkerQ.remove();//GPResourceHome.commonState.notificationQ.waitUntilNotEmpty(); boolean sentOK = false; if (gpResource != null && gpResource.taskQ != null && gpResource.taskPendQ != null && (gpResource.taskQ.size() + gpResource.taskPendQ.size()) > 0) // if (gpResource != null) { Task task = null; // if (gpResource.DATA_AWARE_SCHEDULER && !gpResource.MAX_CACHE_HIT) if (gpResource.DATA_AWARE_SCHEDULER) { // synchronized(gpResource) // { // task = (Task)gpResource.taskQ.remove(); task = (Task) gpResource.taskQ.removeNoWait(); if (task == null) { task = (Task) gpResource.taskPendQ.remove(); } logger.debug( "GPService:NotificationEngine:sendNotification(): removed task " + task.getExecutable().getId() + " from gpResource.taskQ... gpResource.taskQ.size() = " + gpResource.taskQ.size()); gpResource.taskPendQ.insert(task); logger.debug( "GPService:NotificationEngine:sendNotification(): inserted task " + task.getExecutable().getId() + " into gpResource.taskPendQ... gpResource.taskPendQ.size() = " + gpResource.taskPendQ.size()); // } } logger.debug( "GPService:NotificationEngine:sendNotification(): key = " + String.valueOf(gpResource.resourceKey) + " ..."); // if (gpResourceHome.sendNotification(gpResource.resourceKey)) boolean sendNotificationTest = false; if (gpResourceHome.useTCPCore) { sendNotificationTest = gpResourceHome.sendNotificationTCPCore(gpResource); } // else if (gpResource.DATA_AWARE_SCHEDULER && !gpResource.MAX_CACHE_HIT) else if (gpResource.DATA_AWARE_SCHEDULER) { sendNotificationTest = gpResourceHome.sendNotification(gpResource, task); } /* else if (gpResourceHome.localFork) { sendNotificationTest = gpResourceHome.sendNotificationLocal(gpResource); } */ else { sendNotificationTest = gpResourceHome.sendNotification(gpResource); } if (sendNotificationTest) { setNotificationsSent(); logger.debug( "Notification for key " + String.valueOf(gpResource.resourceKey) + " sent successfully!"); // if (gpResource.DATA_AWARE_SCHEDULER) // { // gpResource.taskPendQ.insert(task); // logger.debug("GPService:NotificationEngine:sendNotification(): inserted task into // gpResource.taskPendQ... gpResource.taskPendQ.size() = " + // gpResource.taskPendQ.size()); // } // insert back in to try again later... this is a hack to ensure that we never run out // of notification messages :) // if (!gpResourceHome.useTCPCore) // if (gpResource != null && gpResource.taskQ != null && (gpResource.taskQ.size() + // gpResource.taskPendQ.size()) > 0 && (gpResource.taskQ.size() + // gpResource.taskPendQ.size()) <= GPResourceHome.maxNumNotificationWorkerThreads*2) // { // logger.debug("there is still work to be collected and we have dipped below the // number of notification threads, insert back into the notification queue..."); // GPResourceHome.commonState.notificationWorkerQ.insert(gpResource); // } } else { logger.debug( "Notification for key " + String.valueOf(gpResource.resourceKey) + " failed!"); // if (gpResource.DATA_AWARE_SCHEDULER && !gpResource.MAX_CACHE_HIT) if (gpResource.DATA_AWARE_SCHEDULER) { // synchronized(gpResource) // { // gpResource.taskPendQ.removeTask(task); // should insert back at the front... fix this // gpResource.taskQ.insertFront(task); // } // logger.debug("GPService:NotificationEngine:sendNotification(): inserted task " + // task.getExecutable().getId() + " into gpResource.taskQ... gpResource.taskQ.size() = // " + gpResource.taskQ.size()); } // insert back in to try again later... // if ((gpResource.taskQ.size() + gpResource.taskPendQ.size()) > 0) // { // logger.debug("there is still work to be collected, insert back into the // notification queue..."); // GPResourceHome.commonState.notificationWorkerQ.insert(gpResource); // used for throtling notifications... /* try { System.currentTimeMillis(); Thread.sleep(20); } catch (Exception sss) { } */ // } } } if (MAX_NOT_PER_SEC > 0 && getNotificationsSent() >= MAX_NOT_PER_SEC) { long timeLeft = NOT_TIME_QUANTA - ct.getElapsedTime(); if (timeLeft > 20) try { logger.debug( getNotificationsSent() + " notifications sent in " + ct.getElapsedTime() + " ms, sleeping for " + timeLeft + " ms"); // System.currentTimeMillis(); Thread.sleep(timeLeft); } catch (Exception sss) { } } if (ct.getElapsedTime() >= NOT_TIME_QUANTA) { if (getNotificationsSent() > 0) { logger.debug( "***NotificationEngineWorker(): " + getNotificationsSent() + " notifications sent to workers in " + ct.getElapsedTime() + " ms, maximum allowed notifications " + MAX_NOT_PER_SEC + " per " + NOT_TIME_QUANTA + " ms..."); } ct.reset(); resetNotificationsSent(); ct.start(); } // if (GPResourceHome.commonState.resourceQ.size() > 0 && // GPResourceHome.commonState.getWaitingTasks() <= 0) if (GPResourceHome.commonState.getWaitingTasks() <= 0) { try { Thread.sleep(100); } catch (Exception e) { if (logger.isDebugEnabled()) e.printStackTrace(); } } } catch (Exception eee) { logger.debug("Error in NotificationEngineWorker thread: " + eee); if (logger.isDebugEnabled()) eee.printStackTrace(); // continue; // if (gpResource != null && gpResource.taskQ != null && gpResource.taskQ.size() + // gpResource.taskPendQ.size() > 0) // if (gpResource != null && gpResource.taskQ != null) // { // logger.debug("there is still work to be collected, insert back into the notification // queue..."); // GPResourceHome.commonState.notificationWorkerQ.insert(gpResource); // } } } }
void contractNodes() { meanDegree = g.getAllEdges().getMaxId() / g.getNodes(); int level = 1; counter = 0; int initSize = sortedNodes.getSize(); int logSize = (int) Math.round(Math.max(10, sortedNodes.getSize() / 100 * logMessagesPercentage)); if (logMessagesPercentage == 0) logSize = Integer.MAX_VALUE; // preparation takes longer but queries are slightly faster with preparation // => enable it but call not so often boolean periodicUpdate = true; StopWatch periodSW = new StopWatch(); int updateCounter = 0; int periodicUpdatesCount = Math.max(10, sortedNodes.getSize() / 100 * periodicUpdatesPercentage); if (periodicUpdatesPercentage == 0) periodicUpdate = false; // disable as preparation is slower and query time does not benefit int lastNodesLazyUpdates = lastNodesLazyUpdatePercentage == 0 ? 0 : sortedNodes.getSize() / 100 * lastNodesLazyUpdatePercentage; StopWatch lazySW = new StopWatch(); // Recompute priority of uncontracted neighbors. // Without neighborupdates preparation is faster but we need them // to slightly improve query time. Also if not applied too often it decreases the shortcut // number. boolean neighborUpdate = true; if (neighborUpdatePercentage == 0) neighborUpdate = false; StopWatch neighborSW = new StopWatch(); LevelGraphStorage lg = ((LevelGraphStorage) g); while (!sortedNodes.isEmpty()) { // periodically update priorities of ALL nodes if (periodicUpdate && counter > 0 && counter % periodicUpdatesCount == 0) { periodSW.start(); sortedNodes.clear(); int len = g.getNodes(); for (int node = 0; node < len; node++) { if (g.getLevel(node) != 0) continue; int priority = oldPriorities[node] = calculatePriority(node); sortedNodes.insert(node, priority); } periodSW.stop(); updateCounter++; } if (counter % logSize == 0) { // TODO necessary? System.gc(); logger.info( Helper.nf(counter) + ", updates:" + updateCounter + ", nodes: " + Helper.nf(sortedNodes.getSize()) + ", shortcuts:" + Helper.nf(newShortcuts) + ", dijkstras:" + Helper.nf(dijkstraCount) + ", t(dijk):" + (int) dijkstraSW.getSeconds() + ", t(period):" + (int) periodSW.getSeconds() + ", t(lazy):" + (int) lazySW.getSeconds() + ", t(neighbor):" + (int) neighborSW.getSeconds() + ", meanDegree:" + (long) meanDegree + ", algo:" + algo.getMemoryUsageAsString() + ", " + Helper.getMemInfo()); dijkstraSW = new StopWatch(); periodSW = new StopWatch(); lazySW = new StopWatch(); neighborSW = new StopWatch(); } counter++; int polledNode = sortedNodes.pollKey(); if (sortedNodes.getSize() < lastNodesLazyUpdates) { lazySW.start(); int priority = oldPriorities[polledNode] = calculatePriority(polledNode); if (!sortedNodes.isEmpty() && priority > sortedNodes.peekValue()) { // current node got more important => insert as new value and contract it later sortedNodes.insert(polledNode, priority); lazySW.stop(); continue; } lazySW.stop(); } // contract! newShortcuts += addShortcuts(polledNode); g.setLevel(polledNode, level); level++; EdgeSkipIterator iter = vehicleAllExplorer.setBaseNode(polledNode); while (iter.next()) { int nn = iter.getAdjNode(); if (g.getLevel(nn) != 0) // already contracted no update necessary continue; if (neighborUpdate && rand.nextInt(100) < neighborUpdatePercentage) { neighborSW.start(); int oldPrio = oldPriorities[nn]; int priority = oldPriorities[nn] = calculatePriority(nn); if (priority != oldPrio) sortedNodes.update(nn, oldPrio, priority); neighborSW.stop(); } if (removesHigher2LowerEdges) lg.disconnect(vehicleAllTmpExplorer, iter); } } // Preparation works only once so we can release temporary data. // The preparation object itself has to be intact to create the algorithm. close(); logger.info( "took:" + (int) allSW.stop().getSeconds() + ", new shortcuts: " + newShortcuts + ", " + prepareWeighting + ", " + prepareEncoder + ", removeHigher2LowerEdges:" + removesHigher2LowerEdges + ", dijkstras:" + dijkstraCount + ", t(dijk):" + (int) dijkstraSW.getSeconds() + ", t(period):" + (int) periodSW.getSeconds() + ", t(lazy):" + (int) lazySW.getSeconds() + ", t(neighbor):" + (int) neighborSW.getSeconds() + ", meanDegree:" + (long) meanDegree + ", initSize:" + initSize + ", periodic:" + periodicUpdatesPercentage + ", lazy:" + lastNodesLazyUpdatePercentage + ", neighbor:" + neighborUpdatePercentage); }
private void start(CmdArgs args) { String action = args.get("action", "").toLowerCase(); args.put("graph.location", "./graph-cache"); if (action.equals("import")) { String vehicle = args.get("vehicle", "car").toLowerCase(); args.put("graph.flagEncoders", vehicle); args.put("osmreader.osm", args.get("datasource", "")); // standard should be to remove disconnected islands args.put("prepare.minNetworkSize", 200); args.put("prepare.minOneWayNetworkSize", 200); GraphHopper hopper = new GraphHopper().init(args); hopper.setCHEnable(false); hopper.importOrLoad(); } else if (action.equals("match")) { GraphHopper hopper = new GraphHopper().init(args); hopper.setCHEnable(false); logger.info("loading graph from cache"); hopper.load("./graph-cache"); FlagEncoder firstEncoder = hopper.getEncodingManager().fetchEdgeEncoders().get(0); GraphHopperStorage graph = hopper.getGraphHopperStorage(); int gpxAccuracy = args.getInt("gpxAccuracy", 15); String instructions = args.get("instructions", ""); logger.info("Setup lookup index. Accuracy filter is at " + gpxAccuracy + "m"); LocationIndexMatch locationIndex = new LocationIndexMatch(graph, (LocationIndexTree) hopper.getLocationIndex(), gpxAccuracy); MapMatching mapMatching = new MapMatching(graph, locationIndex, firstEncoder); mapMatching.setSeparatedSearchDistance(args.getInt("separatedSearchDistance", 500)); mapMatching.setMaxNodesToVisit(args.getInt("maxNodesToVisit", 1000)); mapMatching.setForceRepair(args.getBool("forceRepair", false)); // do the actual matching, get the GPX entries from a file or via stream String gpxLocation = args.get("gpx", ""); File[] files = getFiles(gpxLocation); logger.info("Now processing " + files.length + " files"); StopWatch importSW = new StopWatch(); StopWatch matchSW = new StopWatch(); Translation tr = new TranslationMap().doImport().get(instructions); for (File gpxFile : files) { try { importSW.start(); List<GPXEntry> inputGPXEntries = new GPXFile().doImport(gpxFile.getAbsolutePath()).getEntries(); importSW.stop(); matchSW.start(); MatchResult mr = mapMatching.doWork(inputGPXEntries); matchSW.stop(); System.out.println(gpxFile); System.out.println( "\tmatches:\t" + mr.getEdgeMatches().size() + ", gps entries:" + inputGPXEntries.size()); System.out.println( "\tgpx length:\t" + (float) mr.getGpxEntriesLength() + " vs " + (float) mr.getMatchLength()); System.out.println( "\tgpx time:\t" + mr.getGpxEntriesMillis() / 1000f + " vs " + mr.getMatchMillis() / 1000f); String outFile = gpxFile.getAbsolutePath() + ".res.gpx"; System.out.println("\texport results to:" + outFile); InstructionList il; if (instructions.isEmpty()) { il = new InstructionList(null); } else { AltResponse matchGHRsp = new AltResponse(); Path path = mapMatching.calcPath(mr); new PathMerger().doWork(matchGHRsp, Collections.singletonList(path), tr); il = matchGHRsp.getInstructions(); } new GPXFile(mr, il).doExport(outFile); } catch (Exception ex) { importSW.stop(); matchSW.stop(); logger.error("Problem with file " + gpxFile + " Error: " + ex.getMessage()); } } System.out.println( "gps import took:" + importSW.getSeconds() + "s, match took: " + matchSW.getSeconds()); } else if (action.equals("getbounds")) { String gpxLocation = args.get("gpx", ""); File[] files = getFiles(gpxLocation); BBox bbox = BBox.createInverse(false); for (File gpxFile : files) { List<GPXEntry> inputGPXEntries = new GPXFile().doImport(gpxFile.getAbsolutePath()).getEntries(); for (GPXEntry entry : inputGPXEntries) { if (entry.getLat() < bbox.minLat) { bbox.minLat = entry.getLat(); } if (entry.getLat() > bbox.maxLat) { bbox.maxLat = entry.getLat(); } if (entry.getLon() < bbox.minLon) { bbox.minLon = entry.getLon(); } if (entry.getLon() > bbox.maxLon) { bbox.maxLon = entry.getLon(); } } } System.out.println("max bounds: " + bbox); // show download only for small areas if (bbox.maxLat - bbox.minLat < 0.1 && bbox.maxLon - bbox.minLon < 0.1) { double delta = 0.01; System.out.println( "Get small areas via\n" + "wget -O extract.osm 'http://overpass-api.de/api/map?bbox=" + (bbox.minLon - delta) + "," + (bbox.minLat - delta) + "," + (bbox.maxLon + delta) + "," + (bbox.maxLat + delta) + "'"); } } else { System.out.println( "Usage: Do an import once, then do the matching\n" + "./map-matching action=import datasource=your.pbf\n" + "./map-matching action=match gpx=your.gpx\n" + "./map-matching action=match gpx=.*gpx\n\n" + "Or start in-built matching web service\n" + "./map-matching action=start-server\n\n"); } }
@Test public void getUniqueDeclaredMethods_isFastEnough() { Assume.group(TestGroup.PERFORMANCE); @SuppressWarnings("unused") class C { void m00() {} void m01() {} void m02() {} void m03() {} void m04() {} void m05() {} void m06() {} void m07() {} void m08() {} void m09() {} void m10() {} void m11() {} void m12() {} void m13() {} void m14() {} void m15() {} void m16() {} void m17() {} void m18() {} void m19() {} void m20() {} void m21() {} void m22() {} void m23() {} void m24() {} void m25() {} void m26() {} void m27() {} void m28() {} void m29() {} void m30() {} void m31() {} void m32() {} void m33() {} void m34() {} void m35() {} void m36() {} void m37() {} void m38() {} void m39() {} void m40() {} void m41() {} void m42() {} void m43() {} void m44() {} void m45() {} void m46() {} void m47() {} void m48() {} void m49() {} void m50() {} void m51() {} void m52() {} void m53() {} void m54() {} void m55() {} void m56() {} void m57() {} void m58() {} void m59() {} void m60() {} void m61() {} void m62() {} void m63() {} void m64() {} void m65() {} void m66() {} void m67() {} void m68() {} void m69() {} void m70() {} void m71() {} void m72() {} void m73() {} void m74() {} void m75() {} void m76() {} void m77() {} void m78() {} void m79() {} void m80() {} void m81() {} void m82() {} void m83() {} void m84() {} void m85() {} void m86() {} void m87() {} void m88() {} void m89() {} void m90() {} void m91() {} void m92() {} void m93() {} void m94() {} void m95() {} void m96() {} void m97() {} void m98() {} void m99() {} } StopWatch sw = new StopWatch(); sw.start(); Method[] methods = ReflectionUtils.getUniqueDeclaredMethods(C.class); sw.stop(); long totalMs = sw.getTotalTimeMillis(); assertThat(methods.length, Matchers.greaterThan(100)); assertThat(totalMs, Matchers.lessThan(10L)); }
/** zahájení odpočtu */ public void start() { stopWatch.start(); }