com.google.common.base.Stopwatch#start ( )源码实例Demo

下面列出了com.google.common.base.Stopwatch#start ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: meghanada-server   文件: ASMReflectorTest.java
@Test
public void testReflectAll6() throws Exception {
  ASMReflector asmReflector = ASMReflector.getInstance();
  Stopwatch stopwatch = Stopwatch.createUnstarted();
  {
    File jar = getRTJar();
    Map<String, ClassIndex> index = asmReflector.getClassIndexes(jar);

    String fqcn = "java.util.jar.JarFile";
    final InheritanceInfo info = asmReflector.getReflectInfo(index, fqcn);
    System.out.println(info);
    stopwatch.start();
    List<MemberDescriptor> memberDescriptors1 = asmReflector.reflectAll(info);
    System.out.println(stopwatch.stop());
    System.out.println(memberDescriptors1.size());
    memberDescriptors1.forEach(
        md -> {
          System.out.println(md.getDeclaration());
          // System.out.println(md.declaration);
        });
  }
}
 
源代码2 项目: twill   文件: RestartRunnableTestRun.java
private void waitForInstance(TwillController controller, String runnable, String yarnInstanceId,
                             long timeout, TimeUnit timeoutUnit) throws InterruptedException, TimeoutException {
  Stopwatch stopwatch = new Stopwatch();
  stopwatch.start();
  do {
    ResourceReport report = controller.getResourceReport();
    if (report != null && report.getRunnableResources(runnable) != null) {
      for (TwillRunResources resources : report.getRunnableResources(runnable)) {
        if (resources.getContainerId().endsWith(yarnInstanceId)) {
          return;
        }
      }
    }
    TimeUnit.SECONDS.sleep(1);
  } while (stopwatch.elapsedTime(timeoutUnit) < timeout);

  throw new TimeoutException("Timeout reached while waiting for runnable " +
                               runnable + " instance " + yarnInstanceId);
}
 
源代码3 项目: phoenix-tephra   文件: DefaultFenceWait.java
@Override
public void await(long timeout, TimeUnit timeUnit)
  throws TransactionFailureException, InterruptedException, TimeoutException {
  Stopwatch stopwatch = new Stopwatch();
  stopwatch.start();
  long sleepTimeMicros = timeUnit.toMicros(timeout) / 10;
  // Have sleep time to be within 1 microsecond and 500 milliseconds
  sleepTimeMicros = Math.max(Math.min(sleepTimeMicros, 500 * 1000), 1);
  while (stopwatch.elapsedTime(timeUnit) < timeout) {
    txContext.start();
    try {
      txContext.finish();
      return;
    } catch (TransactionFailureException e) {
      LOG.error("Got exception waiting for fence. Sleeping for {} microseconds", sleepTimeMicros, e);
      txContext.abort();
      TimeUnit.MICROSECONDS.sleep(sleepTimeMicros);
    }
  }
  throw new TimeoutException("Timeout waiting for fence");
}
 
public Iterator<ITuple> doSearch(DataRequest dataRequest, CubeInstance cube, StreamingTupleConverter tupleConverter,
        RecordsSerializer recordsSerializer, Node receiver, TupleInfo tupleInfo) throws Exception {
    String queryId = dataRequest.getQueryId();
    logger.info("send query to receiver " + receiver + " with query id:" + queryId);
    String url = "http://" + receiver.getHost() + ":" + receiver.getPort() + "/kylin/api/data/query";

    try {
        String content = JsonUtil.writeValueAsString(dataRequest);
        Stopwatch sw = new Stopwatch();
        sw.start();
        int connTimeout = cube.getConfig().getStreamingRPCHttpConnTimeout();
        int readTimeout = cube.getConfig().getStreamingRPCHttpReadTimeout();
        String msg = restService.postRequest(url, content, connTimeout, readTimeout);

        logger.info("query-{}: receive response from {} take time:{}", queryId, receiver, sw.elapsedMillis());
        if (failedReceivers.containsKey(receiver)) {
            failedReceivers.remove(receiver);
        }
        DataResponse response = JsonUtil.readValue(msg, DataResponse.class);
        logger.info("query-{}: receiver {} profile info:{}", queryId, receiver, response.getProfile());
        return deserializeResponse(tupleConverter, recordsSerializer, cube.getName(), tupleInfo, response);
    } catch (Exception e) {
        logger.error("error when search data from receiver:" + url, e);
        throw e;
    }
}
 
源代码5 项目: meghanada-server   文件: ASMReflectorTest.java
@Test
public void testReflectInner1() throws Exception {
  ASMReflector asmReflector = ASMReflector.getInstance();
  Stopwatch stopwatch = Stopwatch.createUnstarted();
  {
    String fqcn = "java.util.Map$Entry";
    File jar = getRTJar();
    Map<String, ClassIndex> index = asmReflector.getClassIndexes(jar);
    final InheritanceInfo info = asmReflector.getReflectInfo(index, fqcn);
    stopwatch.start();
    System.out.println(info);
    List<MemberDescriptor> memberDescriptors = asmReflector.reflectAll(info);
    System.out.println(stopwatch.stop());
    assertEquals(18, memberDescriptors.size());
    stopwatch.reset();
  }
}
 
源代码6 项目: meghanada-server   文件: ASMReflectorTest.java
@Test
public void testReflectWithGenerics3() throws Exception {
  ASMReflector asmReflector = ASMReflector.getInstance();
  Stopwatch stopwatch = Stopwatch.createUnstarted();
  {
    String fqcn = "java.util.Map<? extends String, ? extends Long>";
    File jar = getRTJar();
    Map<String, ClassIndex> index = asmReflector.getClassIndexes(jar);
    final InheritanceInfo info = asmReflector.getReflectInfo(index, fqcn);

    stopwatch.start();
    List<MemberDescriptor> memberDescriptors = asmReflector.reflectAll(info);
    System.out.println(stopwatch.stop());
    memberDescriptors.forEach(m -> System.out.println(m.getDisplayDeclaration()));
    Config config = Config.load();
    if (config.isJava8()) {
      assertEquals(34, memberDescriptors.size());
    } else {
      assertEquals(47, memberDescriptors.size());
    }
    stopwatch.reset();
  }
}
 
源代码7 项目: grpc-nebula-java   文件: OkHttpClientTransport.java
@Override
public void ping(final PingCallback callback, Executor executor) {
  checkState(frameWriter != null);
  long data = 0;
  Http2Ping p;
  boolean writePing;
  synchronized (lock) {
    if (stopped) {
      Http2Ping.notifyFailed(callback, executor, getPingFailure());
      return;
    }
    if (ping != null) {
      // we only allow one outstanding ping at a time, so just add the callback to
      // any outstanding operation
      p = ping;
      writePing = false;
    } else {
      // set outstanding operation and then write the ping after releasing lock
      data = random.nextLong();
      Stopwatch stopwatch = stopwatchFactory.get();
      stopwatch.start();
      p = ping = new Http2Ping(data, stopwatch);
      writePing = true;
      transportTracer.reportKeepAliveSent();
    }
  }
  if (writePing) {
    frameWriter.ping(false, (int) (data >>> 32), (int) data);
  }
  // If transport concurrently failed/stopped since we released the lock above, this could
  // immediately invoke callback (which we shouldn't do while holding a lock)
  p.addCallback(callback, executor);
}
 
源代码8 项目: turbine   文件: Processing.java
Timer start(Processor processor) {
  Class<? extends Processor> clazz = processor.getClass();
  Stopwatch sw = processorTimers.get(clazz);
  if (sw == null) {
    sw = Stopwatch.createUnstarted();
    processorTimers.put(clazz, sw);
  }
  sw.start();
  return new Timer(sw);
}
 
源代码9 项目: TagRec   文件: GIRPTMCalculator.java
public static BookmarkReader predictSample(String filename, int trainSize, int sampleSize, boolean userBased, boolean resBased) {
	Timer timerThread = new Timer();
	MemoryThread memoryThread = new MemoryThread();
	timerThread.schedule(memoryThread, 0, MemoryThread.TIME_SPAN);
	
	BookmarkReader reader = new BookmarkReader(trainSize, false);
	reader.readFile(filename);	
	List<int[]> predictionValues = new ArrayList<int[]>();
	Stopwatch timer = new Stopwatch();
	timer.start();
	GIRPTMCalculator calculator = new GIRPTMCalculator(reader, trainSize, userBased, resBased);
	timer.stop();
	long trainingTime = timer.elapsed(TimeUnit.MILLISECONDS);
	
	timer.reset();
	timer.start();
	for (int i = trainSize; i < trainSize + sampleSize; i++) { // the test-set
		Bookmark data = reader.getBookmarks().get(i);
		Map<Integer, Double> map = calculator.getRankedTagList(data.getUserID(), data.getResourceID());
		predictionValues.add(Ints.toArray(map.keySet()));
	}
	timer.stop();
	long testTime = timer.elapsed(TimeUnit.MILLISECONDS);
	
	timeString = PerformanceMeasurement.addTimeMeasurement(timeString, true, trainingTime, testTime, sampleSize);		
	String suffix = "_girp";
	if (userBased && resBased) {
		suffix = "_girptm";
	}
	reader.setTestLines(reader.getBookmarks().subList(trainSize, reader.getBookmarks().size()));
	PredictionFileWriter writer = new PredictionFileWriter(reader, predictionValues);
	writer.writeFile(filename + suffix);
	
	timeString = PerformanceMeasurement.addMemoryMeasurement(timeString, false, memoryThread.getMaxMemory());
	timerThread.cancel();
	Utilities.writeStringToFile("./data/metrics/" + filename + suffix + "_TIME.txt", timeString);		
	return reader;
}
 
源代码10 项目: kylin-on-parquet-v2   文件: InMemCubeBuilder2.java
protected CuboidResult scanAndAggregateGridTable(GridTable gridTable, GridTable newGridTable, long parentId,
        long cuboidId, ImmutableBitSet aggregationColumns, ImmutableBitSet measureColumns) throws IOException {
    Stopwatch sw = new Stopwatch();
    sw.start();
    logger.info("Calculating cuboid {}", cuboidId);

    GTAggregateScanner scanner = prepareGTAggregationScanner(gridTable, parentId, cuboidId, aggregationColumns,
            measureColumns);
    GTBuilder builder = newGridTable.rebuild();

    ImmutableBitSet allNeededColumns = aggregationColumns.or(measureColumns);

    GTRecord newRecord = new GTRecord(newGridTable.getInfo());
    int count = 0;
    try {
        for (GTRecord record : scanner) {
            count++;
            for (int i = 0; i < allNeededColumns.trueBitCount(); i++) {
                int c = allNeededColumns.trueBitAt(i);
                newRecord.set(i, record.get(c));
            }
            builder.write(newRecord);
        }
    } finally {
        scanner.close();
        builder.close();
    }
    sw.stop();
    logger.info("Cuboid {} has {} rows, build takes {}ms", cuboidId, count, sw.elapsedMillis());

    return updateCuboidResult(cuboidId, newGridTable, count, sw.elapsedMillis(), 0);
}
 
public static void waitForRuns(int runs, int timeout, TimeUnit unit) throws Exception {
  long timeoutMillis = unit.toMillis(timeout);
  Stopwatch stopWatch = new Stopwatch();
  stopWatch.start();
  while (pruneRuns < runs && stopWatch.elapsedMillis() < timeoutMillis) {
    TimeUnit.MILLISECONDS.sleep(100);
  }
}
 
@Override
public void benchmarkOne(GraphDatabaseType type, int scenarioNumber)
{
    GraphDatabase<?,?,?,?> graphDatabase = Utils.createDatabaseInstance(bench, type);
    graphDatabase.open();
    Stopwatch watch = new Stopwatch();
    watch.start();
    graphDatabase.findAllNodeNeighbours();
    graphDatabase.shutdown();
    times.get(type).add((double) watch.elapsed(TimeUnit.MILLISECONDS));
}
 
源代码13 项目: dropwizard-guicey   文件: ModulesSupport.java
/**
 * Search for extensions in guice bindings (directly declared in modules).
 * Only user provided modules are analyzed. Overriding modules are not analyzed.
 * <p>
 * Use guice SPI. In order to avoid duplicate analysis in injector creation time, wrap
 * parsed elements as new module (and use it instead of original modules). Also, if
 * bound extension is disabled, target binding is simply removed (in order to
 * provide the same disable semantic as with usual extensions).
 *
 * @param context configuration context
 * @return list of repackaged modules to use
 */
private static List<Module> analyzeModules(final ConfigurationContext context,
                                           final Stopwatch modulesTimer) {
    List<Module> modules = context.getNormalModules();
    final Boolean configureFromGuice = context.option(AnalyzeGuiceModules);
    // one module mean no user modules registered
    if (modules.size() > 1 && configureFromGuice) {
        // analyzing only user bindings (excluding overrides and guicey technical bindings)
        final GuiceBootstrapModule bootstrap = (GuiceBootstrapModule) modules.remove(modules.size() - 1);
        try {
            // find extensions and remove bindings if required (disabled extensions)
            final Stopwatch gtime = context.stat().timer(Stat.BindingsResolutionTime);
            final List<Element> elements = new ArrayList<>(
                    Elements.getElements(context.option(InjectorStage), modules));
            gtime.stop();

            // exclude analysis time from modules processing time (it's installer time)
            modulesTimer.stop();
            analyzeAndFilterBindings(context, modules, elements);
            modulesTimer.start();

            // wrap raw elements into module to avoid duplicate work on guice startup and put back bootstrap
            modules = Arrays.asList(Elements.getModule(elements), bootstrap);
        } catch (Exception ex) {
            // better show meaningful message then just fail entire startup with ambiguous message
            // NOTE if guice configuration is not OK it will fail here too, but user will see injector creation
            // error as last error in logs.
            LOGGER.error("Failed to analyze guice bindings - skipping this step. Note that configuration"
                    + " from bindings may be switched off with " + GuiceyOptions.class.getSimpleName() + "."
                    + AnalyzeGuiceModules.name() + " option.", ex);
            // recover and use original modules
            modules.add(bootstrap);
            if (!modulesTimer.isRunning()) {
                modulesTimer.start();
            }
        }
    }
    return modules;
}
 
源代码14 项目: TagRec   文件: MPurCalculator.java
public static List<Map<Integer, Double>> startLanguageModelCreation(BookmarkReader reader, int sampleSize, boolean sorting, boolean userBased, boolean resBased, int beta) {
	int size = reader.getBookmarks().size();
	int trainSize = size - sampleSize;
	
	Stopwatch timer = new Stopwatch();
	timer.start();
	MPurCalculator calculator = new MPurCalculator(reader, trainSize, beta, userBased, resBased);
	timer.stop();
	long trainingTime = timer.elapsed(TimeUnit.MILLISECONDS);
	List<Map<Integer, Double>> results = new ArrayList<Map<Integer, Double>>();
	if (trainSize == size) {
		trainSize = 0;
	}
	
	timer.reset();
	timer.start();
	for (int i = trainSize; i < size; i++) { // the test-set
		Bookmark data = reader.getBookmarks().get(i);
		Map<Integer, Double> map = calculator.getRankedTagList(data.getUserID(), data.getResourceID(), sorting);
		results.add(map);
	}
	timer.stop();
	long testTime = timer.elapsed(TimeUnit.MILLISECONDS);
	
	timeString = PerformanceMeasurement.addTimeMeasurement(timeString, true, trainingTime, testTime, sampleSize);
	return results;
}
 
源代码15 项目: dremio-oss   文件: SplitStageExecutor.java
@Override
public Integer apply(Integer recordsToConsume, Stopwatch javaWatch, Stopwatch gandivaWatch) throws Exception {
  gandivaWatch.start();
  try {
    return nativeFilter.filterBatch(recordsToConsume);
  } finally {
    gandivaWatch.stop();
  }
}
 
源代码16 项目: datacollector   文件: TestRemoteEventHandler.java
@Test
public void testSendingEventClientToServer() throws Exception {
  MessagingJsonToFromDto jsonToFromDto = MessagingJsonToFromDto.INSTANCE;
  List<ClientEvent> ackEventJsonList = new ArrayList<ClientEvent>();
  MockRemoteDataCollector mockRemoteDataCollector = new MockRemoteDataCollector();
  mockRemoteDataCollector.putDummyPipelineStatus = true;
  mockRemoteDataCollector.putRemotePipelines = true;
  MockBaseEventSenderReceiver mockBaseEventSenderReceiver = new MockBaseEventSenderReceiver();
  Stopwatch stopwatch = Stopwatch.createUnstarted();
  stopwatch.start();
  final MockBaseEventSenderReceiver eventSenderReceiver = new MockBaseEventSenderReceiver();
  final StageLibraryTask mockStageLibraryTask = new MockStages.MockStageLibraryTask.Builder().build();
  final RuntimeInfo mockRuntimeInfo = Mockito.mock(RuntimeInfo.class);
  final RemoteEventHandlerTask remoteEventHandlerTask = new RemoteEventHandlerTask(
      mockRemoteDataCollector,
      new SafeScheduledExecutorService(1, "testSendingEventClientToServer"),
      new SafeScheduledExecutorService(1, "testSendingEventClientToServer"),
      mockStageLibraryTask,
      buildInfo,
      mockRuntimeInfo,
      new Configuration()
  );
  EventHandlerCallable remoteEventHandler = remoteEventHandlerTask.new EventHandlerCallable(
      mockRemoteDataCollector,
      mockBaseEventSenderReceiver,
      jsonToFromDto,
      ackEventJsonList,
      new ArrayList<ClientEvent>(),
      null,
      null,
      -1,
      Arrays.asList("JOB_RUNNER"),
      ImmutableList.of("jobrunner-app", "timeseries-app"),
      new HashMap<>(),
      stopwatch,
      60000,
      -1,
      new HashMap<>(),
      mockRuntimeInfo
  );
  remoteEventHandler.callRemoteControl();
  assertEquals(1, mockBaseEventSenderReceiver.clientJson.size());
  ClientEventJson clientEventJson = mockBaseEventSenderReceiver.clientJson.get(0);
  PipelineStatusEventJson pipelineStatusEventJson = jsonToFromDto.deserialize(
      clientEventJson.getPayload(),
      new TypeReference<PipelineStatusEventJson>() {
      }
  );
  assertEquals("remote", pipelineStatusEventJson.getName());
  mockRemoteDataCollector.putRemotePipelines = false;
  Thread.sleep(10);
  remoteEventHandler = remoteEventHandlerTask.new EventHandlerCallable(
      mockRemoteDataCollector,
      mockBaseEventSenderReceiver,
      jsonToFromDto,
      ackEventJsonList,
      new ArrayList<ClientEvent>(),
      null,
      null,
      -1,
      Arrays.asList("JOB_RUNNER"),
      ImmutableList.of("jobrunner-app", "timeseries-app"),
      new HashMap<>(),
      stopwatch,
      5,
      -1,
      new HashMap<>(),
      mockRuntimeInfo
  );
  remoteEventHandler.callRemoteControl();
  assertEquals(2, mockBaseEventSenderReceiver.clientJson.size());
  clientEventJson = mockBaseEventSenderReceiver.clientJson.get(0);
  PipelineStatusEventsJson pipelineStatusEventsJson = jsonToFromDto.deserialize(
      clientEventJson.getPayload(),
      new TypeReference<PipelineStatusEventsJson>() {
      }
  );
  List<PipelineStatusEventJson> pipelineStateInfoList = pipelineStatusEventsJson.getPipelineStatusEventList();
  assertEquals("name1", pipelineStateInfoList.get(0).getName());
  assertEquals("title1", pipelineStateInfoList.get(0).getTitle());
  assertEquals("rev1", pipelineStateInfoList.get(0).getRev());
  assertEquals(PipelineStatusJson.RUNNING, pipelineStateInfoList.get(0).getPipelineStatus());
  assertEquals(10, pipelineStateInfoList.get(0).getRunnerCount());

  assertEquals("name2", pipelineStateInfoList.get(1).getName());
  assertEquals("title2", pipelineStateInfoList.get(1).getTitle());
  assertEquals("rev2", pipelineStateInfoList.get(1).getRev());
  assertEquals(PipelineStatusJson.CONNECTING, pipelineStateInfoList.get(1).getPipelineStatus());
}
 
源代码17 项目: grpc-java   文件: NettyClientHandler.java
/**
 * Sends a PING frame. If a ping operation is already outstanding, the callback in the message is
 * registered to be called when the existing operation completes, and no new frame is sent.
 */
private void sendPingFrameTraced(ChannelHandlerContext ctx, SendPingCommand msg,
    ChannelPromise promise) {
  // Don't check lifecycleManager.getShutdownStatus() since we want to allow pings after shutdown
  // but before termination. After termination, messages will no longer arrive because the
  // pipeline clears all handlers on channel close.

  PingCallback callback = msg.callback();
  Executor executor = msg.executor();
  // we only allow one outstanding ping at a time, so just add the callback to
  // any outstanding operation
  if (ping != null) {
    promise.setSuccess();
    ping.addCallback(callback, executor);
    return;
  }

  // Use a new promise to prevent calling the callback twice on write failure: here and in
  // NettyClientTransport.ping(). It may appear strange, but it will behave the same as if
  // ping != null above.
  promise.setSuccess();
  promise = ctx().newPromise();
  // set outstanding operation
  long data = USER_PING_PAYLOAD;
  Stopwatch stopwatch = stopwatchFactory.get();
  stopwatch.start();
  ping = new Http2Ping(data, stopwatch);
  ping.addCallback(callback, executor);
  // and then write the ping
  encoder().writePing(ctx, false, USER_PING_PAYLOAD, promise);
  ctx.flush();
  final Http2Ping finalPing = ping;
  promise.addListener(new ChannelFutureListener() {
    @Override
    public void operationComplete(ChannelFuture future) throws Exception {
      if (future.isSuccess()) {
        transportTracer.reportKeepAliveSent();
      } else {
        Throwable cause = future.cause();
        if (cause instanceof ClosedChannelException) {
          cause = lifecycleManager.getShutdownThrowable();
          if (cause == null) {
            cause = Status.UNKNOWN.withDescription("Ping failed but for unknown reason.")
                .withCause(future.cause()).asException();
          }
        }
        finalPing.failed(cause);
        if (ping == finalPing) {
          ping = null;
        }
      }
    }
  });
}
 
源代码18 项目: bazel-buildfarm   文件: PipelineStage.java
protected void iterate() throws InterruptedException {
  OperationContext operationContext;
  OperationContext nextOperationContext = null;
  long stallUSecs = 0;
  Stopwatch stopwatch = Stopwatch.createUnstarted();
  try {
    operationContext = take();
    logStart(operationContext.operation.getName());
    stopwatch.start();
    boolean valid = false;
    tickThread = Thread.currentThread();
    try {
      nextOperationContext = tick(operationContext);
      long tickUSecs = stopwatch.elapsed(MICROSECONDS);
      valid = nextOperationContext != null && output.claim(nextOperationContext);
      stallUSecs = stopwatch.elapsed(MICROSECONDS) - tickUSecs;
      // ensure that we clear interrupted if we were supposed to cancel tick
      if (Thread.interrupted() && !tickCancelled()) {
        throw new InterruptedException();
      }
      tickThread = null;
    } catch (InterruptedException e) {
      boolean isTickCancelled = tickCancelled();
      tickThread = null;
      if (valid) {
        output.release();
      }
      if (!isTickCancelled) {
        throw e;
      }
    }
    if (valid) {
      output.put(nextOperationContext);
    } else {
      error.put(operationContext);
    }
  } finally {
    release();
  }
  after(operationContext);
  long usecs = stopwatch.elapsed(MICROSECONDS);
  logComplete(
      operationContext.operation.getName(), usecs, stallUSecs, nextOperationContext != null);
}
 
源代码19 项目: TagRec   文件: ThreeLTCalculator.java
public static BookmarkReader predictSample(String filename, int trainSize, int sampleSize, int d, int beta, boolean userBased, boolean resBased,
		boolean tagBLL, boolean topicBLL, CalculationType cType) {
	
	Timer timerThread = new Timer();
	MemoryThread memoryThread = new MemoryThread();
	timerThread.schedule(memoryThread, 0, MemoryThread.TIME_SPAN);
	
	BookmarkReader reader = new BookmarkReader(trainSize, false);
	reader.readFile(filename);
	
	List<int[]> predictionValues = new ArrayList<int[]>();
	Stopwatch timer = new Stopwatch();
	timer.start();
	ThreeLTCalculator calculator = new ThreeLTCalculator(reader, trainSize, d, beta, userBased, resBased, false, cType);
	timer.stop();
	long trainingTime = timer.elapsed(TimeUnit.MILLISECONDS);
	
	timer.reset();
	timer.start();
	for (int i = trainSize; i < trainSize + sampleSize; i++) { // the test-set
		Bookmark data = reader.getBookmarks().get(i);
		long timestamp = Long.parseLong((data.getTimestamp()));
		Map<Integer, Double> map = calculator.getRankedTagList(data.getUserID(), data.getResourceID(), data.getCategories(), timestamp, 10, tagBLL, topicBLL, true);
		predictionValues.add(Ints.toArray(map.keySet()));
	}
	timer.stop();
	long testTime = timer.elapsed(TimeUnit.MILLISECONDS);
	
	timeString = PerformanceMeasurement.addTimeMeasurement(timeString, true, trainingTime, testTime, sampleSize);		
	String suffix = "_layers";
	if (!userBased) {
		suffix = "_reslayers";
	} else if (!resBased) {
		suffix = "_userlayers";
	}
	if (tagBLL && topicBLL) {
		suffix += "bll";
	} else if (tagBLL) {
		suffix += "tagbll";
	} else if (topicBLL) {
		suffix += "topicbll";
	}
	if (cType == CalculationType.USER_TO_RESOURCE) {
		suffix += "ac";
	}
	
	String outputFile = filename + suffix + "_" + beta + "_" + d;	
	reader.setTestLines(reader.getBookmarks().subList(trainSize, reader.getBookmarks().size()));
	PredictionFileWriter writer = new PredictionFileWriter(reader, predictionValues);
	writer.writeFile(outputFile);
	
	timeString = PerformanceMeasurement.addMemoryMeasurement(timeString, false, memoryThread.getMaxMemory());
	timerThread.cancel();
	Utilities.writeStringToFile("./data/metrics/" + outputFile + "_TIME.txt", timeString);	
	return reader;
}
 
源代码20 项目: dropwizard-guicey   文件: StatsTracker.java
/**
 * If measured first time, returns new instance. For second and following measures returns the same instance
 * (to sum measurements).
 * Assumed proper usage: timer stat provided and returned watch correctly stopped.
 *
 * @param name statistic name
 * @return timer to measure time
 */
public Stopwatch timer(final Stat name) {
    final Stopwatch watch = timers.computeIfAbsent(name, k -> Stopwatch.createUnstarted());
    // if watch was performed before then new time will sum with current
    watch.start();
    return watch;
}