當前位置: 首頁>>代碼示例>>Java>>正文


Java Duration.toMillis方法代碼示例

本文整理匯總了Java中java.time.Duration.toMillis方法的典型用法代碼示例。如果您正苦於以下問題:Java Duration.toMillis方法的具體用法?Java Duration.toMillis怎麽用?Java Duration.toMillis使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在java.time.Duration的用法示例。


在下文中一共展示了Duration.toMillis方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: formatAsElapsed

import java.time.Duration; //導入方法依賴的package包/類
public static String formatAsElapsed() {
    Duration elapsed = Duration.ofMillis(ManagementFactory.getRuntimeMXBean().getUptime());
    long days = elapsed.toDays();
    elapsed = elapsed.minusDays(days);
    long hours = elapsed.toHours();
    elapsed = elapsed.minusHours(hours);
    long minutes = elapsed.toMinutes();
    elapsed = elapsed.minusMinutes(minutes);
    long seconds = elapsed.getSeconds();
    elapsed = elapsed.minusSeconds(seconds);
    long millis = elapsed.toMillis();

    return String.format(TIME_FORMAT,
            days,
            hours,
            minutes,
            seconds,
            millis);
}
 
開發者ID:ViniciusArnhold,項目名稱:ProjectAltaria,代碼行數:20,代碼來源:TimeUtils.java

示例2: comparePerfomanceonSlowMethodWithAndWithoutFilter

import java.time.Duration; //導入方法依賴的package包/類
@Test
public void comparePerfomanceonSlowMethodWithAndWithoutFilter() throws InterruptedException {
	// first requests are always slower, so lets "warm up" first
	stressEndpoint(2, 2, "/unfilteredslowmethod/foo", "your name is: foo", false);
	stressEndpoint(2, 2, "/slowmethod/foo", "your name is: foo", true);
	// cool down a bit ;)
	Thread.sleep(250);
	
	long iterations = 10;
	int threads = 5;
	
	LOG.info("starting test on unfiltered method");
	Duration unfilteredDuration = stressEndpoint(iterations, threads, "/unfilteredslowmethod/foo", "your name is: foo", false);
	LOG.info("starting test on filtered method");
	Duration filteredDuration = stressEndpoint(iterations, threads, "/slowmethod/foo", "your name is: foo", true);
	
	long unfilteredMillis = unfilteredDuration.toMillis();
	long filteredMillis = filteredDuration.toMillis();
	LOG.info("unfiltered slowmethod took: " + unfilteredMillis + "ms for " + iterations + " iterations with "+threads+" threads.");
	LOG.info("slowmethod (filtered) took: " + filteredMillis + "ms for " + iterations + " iterations with "+threads+" threads.");
	
	// make sure the filtered duration is not slower than 25% compared to the unfiltered.
	float factor = (float) unfilteredMillis / filteredMillis;
	LOG.info("filter makes the method slower in a factor of: " + factor);
	assertTrue("filtered method is too slow compared to the unfiltered. did you introduce some costy algorithm somewhere? :p", factor > 0.75f );
}
 
開發者ID:alecalanis,項目名稱:session-to-cookie,代碼行數:27,代碼來源:SpringSessionCookiePerfomanceTest.java

示例3: read

import java.time.Duration; //導入方法依賴的package包/類
@Override
public MessageBatch read(String processor, int channel, int maxSize, Duration maxTimeout) {
    long deadline = System.currentTimeMillis() + maxTimeout.toMillis();
    synchronized (this) {
        Map<Long, Message> tailMap = Collections.emptyMap();
        while (System.currentTimeMillis() < deadline
                && (tailMap = messageLog.tailMap(getLastToken(processor), false)).isEmpty()) {
            try {
                this.wait(deadline - System.currentTimeMillis());
            } catch (InterruptedException e) {
                Thread.interrupted();
                return new MessageBatch(new int[]{0, 1}, Collections.emptyList(), null);
            }
        }
        List<Message> messages = new ArrayList<>(tailMap.values());
        Long lastIndex = messages.isEmpty() ? null : messages.get(messages.size() - 1).getIndex();
        return new MessageBatch(new int[]{0, 1}, messages, lastIndex);
    }
}
 
開發者ID:flux-capacitor-io,項目名稱:flux-capacitor-client,代碼行數:20,代碼來源:InMemoryMessageStore.java

示例4: format

import java.time.Duration; //導入方法依賴的package包/類
public String format(Duration object) {
    if (object.isZero()) {
        return "0";
    }
    if (Duration.ofDays(object.toDays()).equals(object)) {
        return object.toDays() + "d";
    }
    if (Duration.ofHours(object.toHours()).equals(object)) {
        return object.toHours() + "h";
    }
    if (Duration.ofMinutes(object.toMinutes()).equals(object)) {
        return object.toMinutes() + "m";
    }
    if (Duration.ofSeconds(object.getSeconds()).equals(object)) {
        return object.getSeconds() + "s";
    }
    if (Duration.ofMillis(object.toMillis()).equals(object)) {
        return object.toMillis() + "ms";
    }
    return object.toNanos() + "ns";
}
 
開發者ID:papyrusglobal,項目名稱:state-channels,代碼行數:22,代碼來源:DurationConverter.java

示例5: render

import java.time.Duration; //導入方法依賴的package包/類
@Override
public void render(Instant now, Graphics2D g, CharacterPosition pos, Riho riho) {
    Duration currentLoopTime = Duration.between(getLoopStartTime(), now);

    int posY = pos.getY() + 40;
    long millis = currentLoopTime.toMillis();

    float alpha = 1.0f;
    if (millis < startMoveTime) {
        double a = ImageUtil.defaultScale(60) * Math.sin(millis / (startMoveTime * 2) * Math.PI * 2);
        posY -= a;
    } else if (millis < startMoveTime + waitTime) {
        // ignored
    } else {
        alpha = Math.max(((float)loopTime - millis) / (float)loopTime, 0);
    }
    ImageUtil.drawImage(g, image, pos.getX() + ImageUtil.defaultScale(340), posY, alpha);

    if (loopTime < millis) {
        nextLoop();
    }
}
 
開發者ID:orekyuu,項目名稱:Riho,代碼行數:23,代碼來源:QuestionRenderer.java

示例6: getFormattedTime

import java.time.Duration; //導入方法依賴的package包/類
private static String getFormattedTime(Duration duration) {
  msElapsed = duration.toMillis();
  secondsElapsed = msElapsed / 1000;
  seconds = (int) secondsElapsed % 60;
  minutes = (int) (secondsElapsed / 60) % 60;
  hours = (int) (secondsElapsed / 3600) % 24;
  days = (int) (secondsElapsed / 86400) % 365;
  years = (int) (secondsElapsed / 31536000);

  sb = new StringBuilder();
  sb.append(years == 0 ? ""
      : (days == 0 && hours == 0 && minutes == 0 && seconds == 0 ? years + (years == 1 ? " year "
          : " years ")
          : years + (years == 1 ? " year, " : " years, ")));
  sb.append(days == 0 ? ""
      : (hours == 0 && minutes == 0 && seconds == 0 ? days + (days == 1 ? " day " : " days ")
          : days + (days == 1 ? " day, " : " days, ")));
  if (years == 0 && days == 0) {
    if (hours == 0) {
      if (minutes == 0) {
        sb.append(String.format("%ds", seconds));
      } else {
        sb.append(
            String.format("%d:%02d", minutes, seconds) + " (" + minutes + "m" + seconds + "s"
                + ")");
      }
    } else {
      sb.append(
          String.format("%d:%02d:%02d", hours, minutes, seconds) + " (" + hours + "h" + minutes
              + "m" + seconds + "s" + ")");
    }
  } else {
    sb.append(hours == 0 ? "" : hours + "h");
    sb.append(minutes == 0 ? "" : minutes + "m");
    sb.append(seconds == 0 ? "" : seconds + "s");
  }
  return sb.toString().trim().replaceAll("\\s+", " ");
}
 
開發者ID:Svetroid,項目名稱:Hobbes-v1,代碼行數:39,代碼來源:UptimeTracker.java

示例7: render

import java.time.Duration; //導入方法依賴的package包/類
@Override
public void render(Instant now, Graphics2D g, CharacterPosition pos, Riho riho) {
    Duration currentLoopTime = Duration.between(getLoopStartTime(), now);
    long millis = currentLoopTime.toMillis();

    int posY = pos.getY() + ImageUtil.defaultScale(50);
    double a = Math.min(millis, loopTime - waitTime) / (loopTime - waitTime);

    posY += ImageUtil.defaultScale(20) * a;
    ImageUtil.drawImage(g, image, pos.getX() + ImageUtil.defaultScale(110), posY, Math.max(0, Math.min(1, a)));
    if (loopTime < millis) {
        nextLoop();
    }
}
 
開發者ID:orekyuu,項目名稱:Riho,代碼行數:15,代碼來源:DropRenderer.java

示例8: render

import java.time.Duration; //導入方法依賴的package包/類
@Override
public void render(Instant now, Graphics2D g, CharacterPosition pos, Riho riho) {
    Duration currentLoopTime = Duration.between(getLoopStartTime(), now);
    long millis = currentLoopTime.toMillis();

    BufferedImage image = images[(int) ((millis / 200) % 2)];
    ImageUtil.drawImage(g, image, pos.getX() - ImageUtil.defaultScale(25), pos.getY() + ImageUtil.defaultScale(200), fadeAnim.getValue(now));

    if (currentLoopTime.compareTo(ANIM_DURATION) > 0) {
        nextLoop();
        fadeAnim.resetAndRestart(now);
    }
}
 
開發者ID:orekyuu,項目名稱:Riho,代碼行數:14,代碼來源:SweatRenderer.java

示例9: toUnit

import java.time.Duration; //導入方法依賴的package包/類
public static long toUnit(TemporalUnit unit, Duration duration) {
    switch((ChronoUnit) unit) {
        case NANOS:     return duration.toNanos();
        case MICROS:    return toMicros(duration);
        case MILLIS:    return duration.toMillis();
        case SECONDS:   return duration.getSeconds();
    }

    if(unit.getDuration().getNano() == 0) {
        return duration.getSeconds() / unit.getDuration().getSeconds();
    }

    throw new IllegalArgumentException("Unsupported sub-second unit " + unit);
}
 
開發者ID:OvercastNetwork,項目名稱:ProjectAres,代碼行數:15,代碼來源:TimeUtils.java

示例10: within

import java.time.Duration; //導入方法依賴的package包/類
@Override
public final Future<T> within(final Duration timeout, final ScheduledExecutorService scheduler,
    final Throwable exception) {
  if (timeout.toMillis() == Long.MAX_VALUE)
    return this;

  final WithinPromise<T> p = new WithinPromise<>(this, timeout, scheduler, exception);
  respond(p);
  return p;
}
 
開發者ID:traneio,項目名稱:future,代碼行數:11,代碼來源:Promise.java

示例11: buildMessage

import java.time.Duration; //導入方法依賴的package包/類
private static String buildMessage(DatarouterHttpResponse response, Duration duration){
	String message = "HTTP response returned with status code " + response.getStatusCode();
	Header header = response.getFirstHeader(X_EXCEPTION_ID);
	if(header != null){
		message += " and exception id " + header.getValue();
	}
	message += " after " + duration.toMillis() + "ms";
	message += " with entity:\n" + response.getEntity();
	return message;
}
 
開發者ID:hotpads,項目名稱:datarouter,代碼行數:11,代碼來源:DatarouterHttpResponseException.java

示例12: create

import java.time.Duration; //導入方法依賴的package包/類
public static RegularTimeSeriesIndex create(Interval interval, Duration spacing) {
    return new RegularTimeSeriesIndex(interval.getStart().toEpochMilli(), interval.getEnd().toEpochMilli(),
                                      spacing.toMillis());
}
 
開發者ID:powsybl,項目名稱:powsybl-core,代碼行數:5,代碼來源:RegularTimeSeriesIndex.java

示例13: requireNonNegative

import java.time.Duration; //導入方法依賴的package包/類
private static Duration requireNonNegative(Duration duration) {
  if (duration.toMillis() < 0) {
    throw new IllegalArgumentException("Negative duration: " + duration);
  }
  return duration;
}
 
開發者ID:google,項目名稱:mug,代碼行數:7,代碼來源:Retryer.java

示例14: KeyDerivationTasks

import java.time.Duration; //導入方法依賴的package包/類
public KeyDerivationTasks(KeyCrypterScrypt scrypt, String password, @Nullable Duration targetTime) {
    keyDerivationTask = new Task<KeyParameter>() {
        @Override
        protected KeyParameter call() throws Exception {
            long start = System.currentTimeMillis();
            try {
                log.info("Started key derivation");
                KeyParameter result = scrypt.deriveKey(password);
                timeTakenMsec = (int) (System.currentTimeMillis() - start);
                log.info("Key derivation done in {}ms", timeTakenMsec);
                return result;
            } catch (Throwable e) {
                log.error("Exception during key derivation", e);
                throw e;
            }
        }
    };

    // And the fake progress meter ... if the vals were calculated correctly progress bar should reach 100%
    // a brief moment after the keys were derived successfully.
    progressTask = new Task<Void>() {
        private KeyParameter aesKey;

        @Override
        protected Void call() throws Exception {
            if (targetTime != null) {
                long startTime = System.currentTimeMillis();
                long curTime;
                long targetTimeMillis = targetTime.toMillis();
                while ((curTime = System.currentTimeMillis()) < startTime + targetTimeMillis) {
                    double progress = (curTime - startTime) / (double) targetTimeMillis;
                    updateProgress(progress, 1.0);

                    // 60fps would require 16msec sleep here.
                    Uninterruptibles.sleepUninterruptibly(20, TimeUnit.MILLISECONDS);
                }
                // Wait for the encryption thread before switching back to main UI.
                updateProgress(1.0, 1.0);
            } else {
                updateProgress(-1, -1);
            }
            aesKey = keyDerivationTask.get();
            return null;
        }

        @Override
        protected void succeeded() {
            checkGuiThread();
            onFinish(aesKey, timeTakenMsec);
        }
    };
    progress = progressTask.progressProperty();
}
 
開發者ID:Techsoul192,項目名稱:legendary-guide,代碼行數:54,代碼來源:KeyDerivationTasks.java

示例15: test_toMillis_tooBig

import java.time.Duration; //導入方法依賴的package包/類
@Test(expectedExceptions=ArithmeticException.class)
public void test_toMillis_tooBig() {
    Duration test = Duration.ofSeconds(Long.MAX_VALUE / 1000, ((Long.MAX_VALUE % 1000) + 1) * 1000000);
    test.toMillis();
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:6,代碼來源:TCKDuration.java


注:本文中的java.time.Duration.toMillis方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。