Java Code Examples for org.apache.commons.lang.time.StopWatch#start()
The following examples show how to use
org.apache.commons.lang.time.StopWatch#start() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StandardStringDigesterThreadedTest.java From jasypt with Apache License 2.0 | 6 votes |
public static void main(String[] args) { try { StandardStringDigesterThreadedTest test = new StandardStringDigesterThreadedTest(); System.out.println("Starting test"); StopWatch sw = new StopWatch(); sw.start(); test.testThreadedDigest(); sw.stop(); System.out.println("Test finished in: " + sw.toString()); } catch (Exception e) { e.printStackTrace(); } }
Example 2
Source File: FbRunner.java From freebencher with Apache License 2.0 | 6 votes |
private void doIt() { boolean successful = false; StopWatch stopWatch = new StopWatch(); stopWatch.start(); try { successful = job.getTarget().invoke(); } catch (Exception e) { successful = false; } stopWatch.stop(); if (successful) { job.getResult().getSuccessfulTests().incrementAndGet(); } else { job.getResult().getFailedTests().incrementAndGet(); } job.getResult() .addSingleTestResult(successful, stopWatch.getTime()); int results = job.getResult().getNumOfTests(); if (results != 0 && !job.getOptions().isQuiet() && (job.getResult().getNumOfTests() % 100 == 0)) { System.err.printf("%d/%d are done\n", results, job.getOptions() .getNumOfTests()); } }
Example 3
Source File: CacheService.java From SkyEye with GNU General Public License v3.0 | 6 votes |
/** * 将数据库中的配置表进行缓存 */ private void loadCache() { StopWatch sw = new StopWatch(); sw.start(); LOGGER.info("start load config to cache"); Iterable<NameInfo> nameInfos = this.nameInfoRepository.findAll(); for (Iterator<NameInfo> it = nameInfos.iterator(); it.hasNext();) { NameInfo nameInfo = it.next(); this.setOps.add(mapping.get(nameInfo.getNameInfoPK().getType()), nameInfo.getNameInfoPK().getName()); } sw.stop(); LOGGER.info("load config to cache end, cost {} ms", sw.getTime()); }
Example 4
Source File: JdbcEntityReaderImpl.java From eagle with Apache License 2.0 | 6 votes |
@Override public <E> List<E> query(List<String> ids) throws Exception { PrimaryKeyCriteriaBuilder criteriaBuilder = new PrimaryKeyCriteriaBuilder(ids,this.jdbcEntityDefinition.getJdbcTableName()); Criteria criteria = criteriaBuilder.build(); String displaySql = SqlBuilder.buildQuery(criteria).getDisplayString(); if(LOG.isDebugEnabled()) LOG.debug("Querying: " + displaySql); EntityRecordMapper recordMapper = new EntityRecordMapper(jdbcEntityDefinition); final StopWatch stopWatch = new StopWatch(); List<E> result; try { stopWatch.start(); TorqueStatementPeerImpl peer = ConnectionManagerFactory.getInstance().getStatementExecutor(); criteria.addSelectColumn(new ColumnImpl(jdbcEntityDefinition.getJdbcTableName(),"*")); result = peer.delegate().doSelect(criteria, recordMapper); LOG.info(String.format("Read %s records in %s ms (sql: %s)",result.size(),stopWatch.getTime(),displaySql)); }catch (Exception ex){ LOG.error("Failed to query by: "+displaySql+", due to: "+ex.getMessage(),ex); throw new IOException("Failed to query by: "+displaySql,ex); }finally { stopWatch.stop(); } return result; }
Example 5
Source File: CacheService.java From SkyEye with GNU General Public License v3.0 | 6 votes |
/** * 将数据库中的配置表进行缓存 */ private void loadCache() { StopWatch sw = new StopWatch(); sw.start(); LOGGER.info("start load config to cache"); Iterable<ServiceInfo> serviceInfos = this.serviceInfoRepository.findAll(); for (Iterator<ServiceInfo> it = serviceInfos.iterator(); it.hasNext();) { ServiceInfo serviceInfo = it.next(); this.setOps.add(SERVICE_INFO_PREFIX, serviceInfo.getSid()); } sw.stop(); LOGGER.info("load config to cache end, cost {} ms", sw.getTime()); }
Example 6
Source File: TestJdbcStorage.java From Eagle with Apache License 2.0 | 6 votes |
/** * TODO: Investigate why writing performance becomes slower as records count increases * * 1) Wrote 100000 records in about 18820 ms for empty table * 2) Wrote 100000 records in about 35056 ms when 1M records in table * * @throws IOException */ //@Test public void testWriterPerformance() throws IOException { StopWatch stopWatch = new StopWatch(); stopWatch.start(); List<TestTimeSeriesAPIEntity> entityList = new ArrayList<TestTimeSeriesAPIEntity>(); int i= 0; while( i++ < 100000){ entityList.add(newInstance()); if(entityList.size()>=1000) { ModifyResult<String> result = storage.create(entityList, entityDefinition); Assert.assertNotNull(result); entityList.clear(); } } stopWatch.stop(); LOG.info("Wrote 100000 records in "+stopWatch.getTime()+" ms"); }
Example 7
Source File: JdbcEntityDeleterImpl.java From Eagle with Apache License 2.0 | 6 votes |
private int deleteByCriteria(Criteria criteria) throws Exception { String displaySql = SqlBuilder.buildQuery(criteria).getDisplayString(); StopWatch stopWatch = new StopWatch(); stopWatch.start(); if(LOG.isDebugEnabled()) LOG.debug("Deleting by query: " + displaySql); try { TorqueStatementPeerImpl peer = ConnectionManagerFactory.getInstance().getStatementExecutor(); int result = peer.delegate().doDelete(criteria); LOG.info(String.format("Deleted %s records in %s ms (sql: %s)",result,stopWatch.getTime(),displaySql)); return result; } catch (Exception e) { LOG.error("Failed to delete by query: "+displaySql,e); throw e; } finally { stopWatch.stop(); } }
Example 8
Source File: ChannelSoftwareHandler.java From spacewalk with GNU General Public License v2.0 | 6 votes |
/** * Private helper method to create a new UpdateErrataCacheEvent and publish it to the * MessageQueue. * @param orgIn The org we're updating. */ private void publishUpdateErrataCacheEvent(Org orgIn) { StopWatch sw = new StopWatch(); if (log.isDebugEnabled()) { log.debug("Updating errata cache"); sw.start(); } UpdateErrataCacheEvent uece = new UpdateErrataCacheEvent(UpdateErrataCacheEvent.TYPE_ORG); uece.setOrgId(orgIn.getId()); MessageQueue.publish(uece); if (log.isDebugEnabled()) { sw.stop(); log.debug("Finished Updating errata cache. Took [" + sw.getTime() + "]"); } }
Example 9
Source File: StreamWindowBenchmarkTest.java From eagle with Apache License 2.0 | 6 votes |
private void benchmarkTest(StreamWindow window, StreamWindowRepository.StorageType storageType) { StopWatch stopWatch = new StopWatch(); stopWatch.start(); LOGGER.info("\n===== Benchmark Test for {} ({}) =====", window.getClass().getSimpleName(), storageType); metricReporter.report(); sendDESCOrderedEventsToWindow(window, storageType, 1000); metricReporter.report(); sendDESCOrderedEventsToWindow(window, storageType, 10000); metricReporter.report(); sendDESCOrderedEventsToWindow(window, storageType, 100000); metricReporter.report(); sendDESCOrderedEventsToWindow(window, storageType, 1000000); metricReporter.report(); stopWatch.stop(); LOGGER.info("\n===== Finished in total {} ms =====\n", stopWatch.getTime()); }
Example 10
Source File: PooledStandardStringDigesterThreadedTest.java From jasypt with Apache License 2.0 | 6 votes |
public static void main(String[] args) { try { final int numThreads = Integer.valueOf(args[0]).intValue(); final int numIters = Integer.valueOf(args[1]).intValue(); final int poolSize = Integer.valueOf(args[2]).intValue(); PooledStandardStringDigesterThreadedTest test = new PooledStandardStringDigesterThreadedTest(numThreads, numIters, poolSize); System.out.println("Starting test. NumThreads: " + numThreads + " NumIters: " + numIters + " PoolSize: " + poolSize); StopWatch sw = new StopWatch(); sw.start(); test.testThreadedDigest(); sw.stop(); System.out.println("Test finished in: " + sw.toString()); } catch (Exception e) { e.printStackTrace(); } }
Example 11
Source File: PooledPBEWithMD5AndDESStringEncryptorThreadedTest.java From jasypt with Apache License 2.0 | 6 votes |
public static void main(String[] args) { try { final int numThreads = Integer.valueOf(args[0]).intValue(); final int numIters = Integer.valueOf(args[1]).intValue(); final int poolSize = Integer.valueOf(args[2]).intValue(); PooledPBEWithMD5AndDESStringEncryptorThreadedTest test = new PooledPBEWithMD5AndDESStringEncryptorThreadedTest(numThreads, numIters, poolSize); System.out.println("Starting test. NumThreads: " + numThreads + " NumIters: " + numIters + " PoolSize: " + poolSize); StopWatch sw = new StopWatch(); sw.start(); test.testThreadedDigest(); sw.stop(); System.out.println("Test finished in: " + sw.toString()); } catch (Exception e) { e.printStackTrace(); } }
Example 12
Source File: TestHBaseWriteEntitiesPerformance.java From Eagle with Apache License 2.0 | 5 votes |
@SuppressWarnings("unused") @Test public void testWrite1MLogAPIEntities(){ Date startTime = new Date(); LOG.info("Start time: " + startTime); StopWatch watch = new StopWatch(); watch.start(); List<String> rowKeys = writeEntities(10); Assert.assertNotNull(rowKeys); watch.stop(); Date endTime = new Date(); LOG.info("End time: " + endTime); LOG.info("Totally take " + watch.getTime() * 1.0 / 1000 + " s"); }
Example 13
Source File: CacheService.java From SkyEye with GNU General Public License v3.0 | 5 votes |
/** * 将redis中的配置信息清除 */ private void clearCache() { StopWatch sw = new StopWatch(); sw.start(); LOGGER.info("start clear config cache"); Set<String> keys = this.redisTemplate.keys(CONFIG_PREFIX + Constants.XING_HAO); this.redisTemplate.delete(keys); sw.stop(); LOGGER.info("clear config cache end, cost {} ms", sw.getTime()); }
Example 14
Source File: GenericEntityServiceResource.java From eagle with Apache License 2.0 | 5 votes |
public GenericServiceAPIResponseEntity updateDatabase(Statement<ModifyResult<String>> statement) { GenericServiceAPIResponseEntity<String> response = new GenericServiceAPIResponseEntity<>(); Map<String,Object> meta = new HashMap<>(); StopWatch stopWatch = new StopWatch(); try { stopWatch.start(); DataStorage dataStorage = DataStorageManager.getDataStorageByEagleConfig(); if(dataStorage == null){ LOG.error("Data storage is null"); throw new IllegalDataStorageException("Data storage is null"); } ModifyResult<String> result = statement.execute(dataStorage); if(result.isSuccess()) { List<String> keys =result.getIdentifiers(); if(keys != null) { response.setObj(keys, String.class); meta.put(TOTAL_RESULTS, keys.size()); } else { meta.put(TOTAL_RESULTS, 0); } meta.put(ELAPSEDMS,stopWatch.getTime()); response.setMeta(meta); response.setSuccess(true); } } catch (Exception e) { LOG.error(e.getMessage(), e); response.setException(e); }finally { stopWatch.stop(); } return response; }
Example 15
Source File: GenericEntityServiceResource.java From Eagle with Apache License 2.0 | 4 votes |
@PUT @Consumes({MediaType.MULTIPART_FORM_DATA}) @Produces(MediaType.APPLICATION_JSON) public GenericServiceAPIResponseEntity update(@FormDataParam("file") InputStream fileInputStream, @FormDataParam("file") FormDataContentDisposition cdh, @QueryParam("serviceName") String serviceName){ GenericServiceAPIResponseEntity<String> response = new GenericServiceAPIResponseEntity<String>(); DataStorage dataStorage; Map<String,Object> meta = new HashMap<>(); StopWatch stopWatch = new StopWatch(); try { stopWatch.start(); EntityDefinition entityDefinition = EntityDefinitionManager.getEntityByServiceName(serviceName); if(entityDefinition == null){ throw new IllegalArgumentException("entity definition of service "+serviceName+" not found"); } List<? extends TaggedLogAPIEntity> entities = unmarshalEntitiesByServie(fileInputStream, entityDefinition); dataStorage = DataStorageManager.getDataStorageByEagleConfig(); UpdateStatement updateStatement = new UpdateStatement(entities,entityDefinition); ModifyResult<String> result = updateStatement.execute(dataStorage); if(result.isSuccess()) { List<String> keys =result.getIdentifiers(); if(keys != null) { response.setObj(keys, String.class); meta.put(TOTAL_RESULTS,keys.size()); }else{ meta.put(TOTAL_RESULTS,0); } meta.put(ELAPSEDMS,stopWatch.getTime()); response.setMeta(meta); response.setSuccess(true); } } catch (Exception e) { LOG.error(e.getMessage(), e); response.setException(e); } finally { stopWatch.stop(); } return response; }
Example 16
Source File: Ec2InstanceUpdateHandler.java From soundwave with Apache License 2.0 | 4 votes |
private MessageProcessingResult ensureInstanceTerminated(NotificationEvent event) throws Exception { String instanceId = event.getDetail().getInstanceId(); StopWatch watch = new StopWatch(); watch.start(); MessageProcessingResult result = new MessageProcessingResult(event); try { EsInstance esInstance = cmdbInstanceStore.getInstanceById(instanceId); if (esInstance == null) { logger.warn("Cannot find instance {}. Try to create it", instanceId); ensureInstanceCreated(event); esInstance = cmdbInstanceStore.getInstanceById(instanceId); } if (esInstance != null) { Date now = DateTime.now(DateTimeZone.UTC).toDate(); esInstance.setState(State.TERMINATED.toString()); esInstance.setUpdatedTime(now); esInstance.setTerminateTime(event.getTime()); cmdbInstanceStore.update(esInstance); logger.info("Terminate Instance {}", instanceId); result.setSucceed(true); try { syncWithDailySnapshot(event, esInstance); } catch (Exception ex) { logger.error("Failed to sync with daily snapshot {} with error {}", instanceId, ex.getMessage()); } } else { result.setError(MessageProcessingResult.MessageProcessingError.NOT_EXIST_IN_ES); logger.error("The instance {} doesn't exist and may be invalid", instanceId); } return result; } finally { watch.stop(); result.setDuration(watch.getTime()); } }
Example 17
Source File: GenericEntityServiceResource.java From Eagle with Apache License 2.0 | 4 votes |
/** * * @param query * @param startTime * @param endTime * @param pageSize * @param startRowkey * @param treeAgg * @param timeSeries * @param intervalmin * @param top * @param filterIfMissing * @param parallel * @param metricName * @param verbose * @return */ @GET @Produces(MediaType.APPLICATION_JSON) @SuppressWarnings("unchecked") public GenericServiceAPIResponseEntity search(@QueryParam("query") String query, @QueryParam("startTime") String startTime, @QueryParam("endTime") String endTime, @QueryParam("pageSize") int pageSize, @QueryParam("startRowkey") String startRowkey, @QueryParam("treeAgg") boolean treeAgg, @QueryParam("timeSeries") boolean timeSeries, @QueryParam("intervalmin") long intervalmin, @QueryParam("top") int top, @QueryParam("filterIfMissing") boolean filterIfMissing, @QueryParam("parallel") int parallel, @QueryParam("metricName") String metricName, @QueryParam("verbose") Boolean verbose){ RawQuery rawQuery = RawQuery.build() .query(query) .startTime(startTime) .endTime(endTime) .pageSize(pageSize) .startRowkey(startRowkey) .treeAgg(treeAgg) .timeSeries(timeSeries) .intervalMin(intervalmin) .top(top) .filerIfMissing(filterIfMissing) .parallel(parallel) .metricName(metricName) .verbose(verbose) .done(); QueryStatement queryStatement = new QueryStatement(rawQuery); GenericServiceAPIResponseEntity response = new GenericServiceAPIResponseEntity(); Map<String,Object> meta = new HashMap<>(); DataStorage dataStorage; StopWatch stopWatch = new StopWatch(); try { stopWatch.start(); dataStorage = DataStorageManager.getDataStorageByEagleConfig(); if(dataStorage==null){ LOG.error("Data storage is null"); throw new IllegalDataStorageException("data storage is null"); } QueryResult<?> result = queryStatement.execute(dataStorage); if(result.isSuccess()){ meta.put(FIRST_TIMESTAMP, result.getFirstTimestamp()); meta.put(LAST_TIMESTAMP, result.getLastTimestamp()); meta.put(TOTAL_RESULTS, result.getSize()); meta.put(ELAPSEDMS,stopWatch.getTime()); response.setObj(result.getData()); response.setType(result.getEntityType()); response.setSuccess(true); response.setMeta(meta); return response; } } catch (Exception e) { response.setException(e); LOG.error(e.getMessage(),e); }finally { stopWatch.stop(); } return response; }
Example 18
Source File: NavTest.java From spacewalk with GNU General Public License v2.0 | 4 votes |
public void testDigester() throws Exception { StopWatch st = new StopWatch(); st.start(); NavTree nt = NavDigester.buildTree(TestUtils.findTestData("sitenav.xml")); assertTrue(nt.getTitleDepth() == 0); assertTrue(nt.getLabel().equals("sitenav_unauth")); assertNotNull(nt.getAclMixins()); NavTreeIndex nti = new NavTreeIndex(nt); String testPath = "/rhn/help/index.do"; nti.computeActiveNodes(testPath, null); NavNode bestNode = nti.getBestNode(); assertEquals(bestNode.getName(), "Help Desk"); assertEquals(bestNode.getPrimaryURL(), testPath); log.info("Index Duration: " + st.getTime() / 1000f + " seconds"); RenderEngine nr = new RenderEngine(nti); st.stop(); Renderable[] renderers = new Renderable[3]; renderers[0] = new SidenavRenderer(); renderers[1] = new TopnavRenderer(); renderers[1].setRenderGuard(new DepthGuard(0, 0)); renderers[2] = new TextRenderer(); renderers[2].setRenderGuard(new DepthGuard(1, Integer.MAX_VALUE)); for (int i = 0; i < renderers.length; i++) { log.info("Using Renderable " + renderers[i].getClass() + ":\n" + nr.render(renderers[i])); } log.info("Parse Duration: " + st.getTime() / 1000f + " seconds"); }
Example 19
Source File: ShellUtils.java From zstack with Apache License 2.0 | 4 votes |
public ShellResult run() { StopWatch watch = new StopWatch(); watch.start(); try { if (withSudo) { command = String.format("sudo %s", command); } ProcessBuilder pb = new ProcessBuilder(Arrays.asList("/bin/bash", "-c", command)); if (baseDir == null) { baseDir = System.getProperty("user.home"); } pb.directory(new File(baseDir)); process = pb.start(); command = Utils.maskSensitiveInfo(command); if (!suppressTraceLog && logger.isTraceEnabled()) { logger.debug(String.format("exec shell command[%s]", command)); } Writer stdout; int stdoutLog = stdoutLogStrategy(); if (stdoutLog == LOG_TO_FILE) { stdout = new BufferedWriter(new FileWriter(stdoutFile)); } else if (stdoutLog == LOG_TO_SCREEN) { stdout = new BufferedWriter(new OutputStreamWriter(System.out)); } else { stdout = new StringWriter(); } Writer stderr; int stderrLog = stderrLogStrategy(); if (stderrLog == LOG_TO_FILE) { stderr = new BufferedWriter(new FileWriter(stderrFile)); } else if (stderrLog == LOG_TO_SCREEN) { stderr = new BufferedWriter(new OutputStreamWriter(System.err)); } else { stderr = new StringWriter(); } StreamConsumer stdoutConsumer = new StreamConsumer(process.getInputStream(), new PrintWriter(stdout, true), stdoutLog != LOG_TO_FILE); StreamConsumer stderrConsumer = new StreamConsumer(process.getErrorStream(), new PrintWriter(stderr, true), stderrLog != LOG_TO_FILE); stderrConsumer.start(); stdoutConsumer.start(); process.waitFor(); stderrConsumer.join(TimeUnit.SECONDS.toMillis(30)); stdoutConsumer.join(TimeUnit.SECONDS.toMillis(30)); ShellResult ret = new ShellResult(); ret.setCommand(command); ret.setRetCode(process.exitValue()); if (stderrLog == LOG_TO_STRING) { ret.setStderr(stderr.toString()); } else if (stderrLog == LOG_TO_FILE) { stderr.close(); } if (stdoutLog == LOG_TO_STRING) { ret.setStdout(stdout.toString()); } else if (stdoutLog == LOG_TO_FILE) { stdout.close(); } return ret; } catch (Exception e) { StringBuilder sb = new StringBuilder(); sb.append("Shell command failed:\n"); sb.append(command); throw new ShellException(sb.toString(), e); } finally { if (process != null) { process.destroy(); } watch.stop(); if (!suppressTraceLog && logger.isTraceEnabled()) { logger.trace(String.format("shell command[%s] costs %sms to finish", command, watch.getTime())); } } }
Example 20
Source File: FbRunner.java From freebencher with Apache License 2.0 | 4 votes |
public void run(final FbJob job) { // validate and init data assertNotNull(job, "job cannot be null"); assertNotNull(job.getTarget(), "the test target cannot be null. What you want to test? "); if (job.getOptions() == null) { job.setOptions(FbJobOptions.defaultOptions()); } assertPositive(job.getOptions().getConcurrency(), "concurrency should be > 0"); assertPositive(job.getOptions().getNumOfTests(), "numOfTests should be > 0"); job.setResult(new FbJobResult()); // create a thread pool FbJobOptions options = job.getOptions(); FbJobResult result = job.getResult(); ExecutorService threadPool = Executors.newFixedThreadPool( options.getConcurrency(), new FbThreadFactory()); System.out.println("Test started."); // start working StopWatch stopWatch = new StopWatch(); stopWatch.start(); for (int i = 1; i <= options.getNumOfTests(); i++) { FbCall call = new FbCall(job); threadPool.submit(call); } try { threadPool.shutdown(); System.out.println("Awaiting termination..."); threadPool.awaitTermination(Integer.MAX_VALUE, TimeUnit.DAYS); } catch (InterruptedException e) { // foreget about it } stopWatch.stop(); System.out.println("Test completed."); // fill results result.setTimeTakenForTests(stopWatch.getTime()); result.setConcurrency(options.getConcurrency()); }