List of usage examples for com.google.common.math LongMath divide
@GwtIncompatible("TODO") @SuppressWarnings("fallthrough") public static long divide(long p, long q, RoundingMode mode)
From source file:org.apache.gobblin.data.management.conversion.hive.watermarker.MultiKeyValueLongWatermark.java
@Override public short calculatePercentCompletion(Watermark lowWatermark, Watermark highWatermark) { Preconditions.checkArgument(//w w w .j a v a2s . c o m lowWatermark instanceof MultiKeyValueLongWatermark && highWatermark instanceof MultiKeyValueLongWatermark, String.format("lowWatermark and highWatermark are not instances of %s", MultiKeyValueLongWatermark.class.getSimpleName())); MultiKeyValueLongWatermark low = (MultiKeyValueLongWatermark) lowWatermark; MultiKeyValueLongWatermark high = (MultiKeyValueLongWatermark) highWatermark; long total = 0; long pulled = 0; for (Map.Entry<String, Long> entry : low.watermarks.entrySet()) { if (high.watermarks.containsKey(entry.getKey())) { total += (high.watermarks.get(entry.getKey()) - entry.getValue()); } } for (Map.Entry<String, Long> entry : low.watermarks.entrySet()) { if (this.watermarks.containsKey(entry.getKey())) { pulled += (this.watermarks.get(entry.getKey()) - entry.getValue()); } } if (pulled > total) { return 100; } return (short) LongMath.divide(pulled * 100, total, RoundingMode.CEILING); }
From source file:com.deb.MemoryBenchMarkJsonDocument.java
/** * During base calculation map is empty. After that map is populated. * Returns the memory usage including reference objects. * //from w w w . j a v a 2 s . c o m * @param label * - (Caffeine, Guava, PandaCache) * @param map * - passed map. * @return total memory usage. */ private String[] evaluate(String label, Map<String, JsonDocument> map) { long base = meter.measureDeep(map); map.putAll(workingSet); long populated = meter.measureDeep(map); long noOfChildren = meter.countChildren(map); long entryOverhead = 2 * FUZZY_SIZE * meter.measureDeep(workingSet.keySet().iterator().next()); long perEntry = LongMath.divide(populated - entryOverhead - base, FUZZY_SIZE, RoundingMode.HALF_EVEN); perEntry += ((perEntry & 1) == 0) ? 0 : 1; long aligned = ((perEntry % 8) == 0) ? perEntry : ((1 + perEntry / 8) * 8); return new String[] { label, String.format("%,d bytes", base), String.format("%,d bytes (%,d aligned)", perEntry, aligned), String.format("%,d ", noOfChildren) }; }
From source file:com.deb.MemoryBenchMarkGSON.java
/** * During base calculation map is empty. After that map is populated. * Returns the memory usage including reference objects. * //from ww w .j a va 2s . c om * @param label * - (Caffeine, Guava, PandaCache) * @param map * - passed map. * @return total memory usage. */ private String[] evaluate(String label, Map<String, JsonObject> map) { long base = meter.measureDeep(map); map.putAll(workingSet); long populated = meter.measureDeep(map); long noOfChilderen = meter.countChildren(map); long entryOverhead = 2 * FUZZY_SIZE * meter.measureDeep(workingSet.keySet().iterator().next()); long perEntry = LongMath.divide(populated - entryOverhead - base, FUZZY_SIZE, RoundingMode.HALF_EVEN); perEntry += ((perEntry & 1) == 0) ? 0 : 1; long aligned = ((perEntry % 8) == 0) ? perEntry : ((1 + perEntry / 8) * 8); return new String[] { label, String.format("%,d bytes", base), String.format("%,d bytes (%,d aligned)", perEntry, aligned), String.format("%,d ", noOfChilderen) }; }
From source file:org.terasology.mm.aether.LoggingTransferListener.java
protected long toKB(long bytes) { return LongMath.divide(bytes, 1024, RoundingMode.HALF_UP); }
From source file:io.opencensus.common.Timestamp.java
private static long floorDiv(long x, long y) { return LongMath.divide(x, y, RoundingMode.FLOOR); }
From source file:com.turn.ttorrent.protocol.torrent.TorrentCreator.java
/** * Return the concatenation of the SHA-1 hashes of a file's pieces. * * <p>/* ww w. jav a 2s . c o m*/ * Hashes the given file piece by piece using the default Torrent piece * length (see {@link #PIECE_LENGTH}) and returns the concatenation of * these hashes, as a string. * </p> * * <p> * This is used for creating Torrent meta-info structures from a file. * </p> * * @param files The file to hash. */ @Nonnull @VisibleForTesting public static byte[] hashFiles(Executor executor, List<File> files, long nbytes, int pieceLength) throws InterruptedException, IOException { int npieces = Ints.checkedCast(LongMath.divide(nbytes, pieceLength, RoundingMode.CEILING)); // (int) Math.ceil((double) nbytes / pieceLength); byte[] out = new byte[Torrent.PIECE_HASH_SIZE * npieces]; CountDownLatch latch = new CountDownLatch(npieces); ByteBuffer overflow = ByteBuffer.allocate(pieceLength); Stopwatch stopwatch = Stopwatch.createStarted(); int piece = 0; for (File file : files) { logger.info("Hashing data from {} ({} pieces)...", new Object[] { file.getName(), LongMath.divide(file.length(), pieceLength, RoundingMode.CEILING) }); MappedByteBuffer map = Files.map(file, FileChannel.MapMode.READ_ONLY); int step = 10; while (map.remaining() > pieceLength) { map.limit(map.position() + pieceLength); ByteBuffer buffer = map.slice(); map.position(map.limit()); map.limit(map.capacity()); executor.execute(new ChunkHasher(out, piece, latch, buffer)); piece++; if (map.position() / (double) map.capacity() * 100f > step) { logger.info(" ... {}% complete", step); step += 10; } } while (map.hasRemaining()) { int length = Math.min(map.remaining(), overflow.remaining()); map.limit(map.position() + length); overflow.put(map); map.position(map.limit()); map.limit(map.capacity()); if (!overflow.hasRemaining()) { overflow.flip(); executor.execute(new ChunkHasher(out, piece, latch, overflow)); overflow = ByteBuffer.allocate(pieceLength); piece++; } } } // Hash the last bit, if any if (overflow.position() > 0) { overflow.flip(); executor.execute(new ChunkHasher(out, piece, latch, overflow)); piece++; } // Wait for hashing tasks to complete. latch.await(); logger.info("Hashed {} file(s) ({} bytes) in {} pieces ({} expected) in {}.", new Object[] { files.size(), nbytes, piece, npieces, stopwatch }); if (npieces != piece) throw new IllegalStateException("Unexpected piece count " + piece + "; expected " + npieces); return out; }
From source file:com.tkmtwo.timex.WallClock.java
/** * Returns a copy of this <code>WallClock</code> plus * the specified <code>Duration</code>. * <p>//from w w w . j a va2s.co m * * * @param d an <code>Duration</code> representing the amount of time * @param rm a <code>RoundingMode</code> used to deal with long to int division * @return a <code>WallClock</code> value */ public WallClock plus(Duration d, RoundingMode rm) { checkNotNull(d, "Need a Duration."); checkNotNull(rm, "Need a RoundingMode."); return plus(Ints.checkedCast(LongMath.divide(d.getMillis(), 1000L, rm))); }
From source file:com.tkmtwo.timex.WallClock.java
/** * Returns a copy of this <code>WallClock</code> minus * the specified <code>Duration</code>. * <p>//from w ww . jav a2s.co m * * * @param d an <code>Duration</code> representing the amount of time * @param rm a <code>RoundingMode</code> used to deal with long to int division * @return a <code>WallClock</code> value */ public WallClock minus(Duration d, RoundingMode rm) { checkNotNull(d, "Need a Duration."); checkNotNull(rm, "Need a RoundingMode."); return minus(Ints.checkedCast(LongMath.divide(d.getMillis(), 1000L, rm))); }
From source file:com.oodrive.nuage.utils.Files.java
/** * Gets the remaining percentage of usable space for a given {@link FileStore}. * /* w ww . jav a2 s. c om*/ * This uses the {@link FileStore#getUsableSpace()} and {@link FileStore#getTotalSpace()} methods to compute the * remaining usable storage space. * * @param fileStore * the file store for which to compute the value * @return the remaining percentage of usable storage space, rounded down to integer percentage points * @throws IOException * if reading the corresponding file store properties fails */ public static final int getRemainingUsablePercentage(final FileStore fileStore) throws IOException { final long usedSpace = fileStore.getUsableSpace(); final long totalSpace = fileStore.getTotalSpace(); return (int) LongMath.divide(usedSpace * 100L, totalSpace, RoundingMode.DOWN); }
From source file:org.apache.phoenix.schema.types.PDataType.java
/** * Deserialize a variable length byte array into a BigDecimal. Note that because of the normalization that gets done * to the scale, if you roundtrip a BigDecimal, it may not be equal before and after. However, the before and after * number will always compare to be equal (i.e. <nBefore>.compareTo(<nAfter>) == 0) * * @param bytes/*from www . j ava 2 s . co m*/ * the bytes containing the number * @param offset * the offset into the byte array * @param length * the length of the serialized BigDecimal * @return the BigDecimal value. */ protected static BigDecimal toBigDecimal(byte[] bytes, int offset, int length) { // From exponent byte back to scale: (<exponent byte> & 0x7F) - 65) * 2 // For example, (((-63 & 0x7F) - 65) & 0xFF) * 2 = 0 // Another example: ((-64 & 0x7F) - 65) * 2 = -2 (then swap the sign for the scale) // If number is negative, going from exponent byte back to scale: (byte)((~<exponent byte> - 65 - 128) * 2) // For example: new BigDecimal(new BigInteger("-1"), -2); // (byte)((~61 - 65 - 128) * 2) = 2, so scale is -2 // Potentially, when switching back, the scale can be added by one and the trailing zero dropped // For digits, just do a mod 100 on the BigInteger. Use long if BigInteger fits if (length == 1 && bytes[offset] == ZERO_BYTE) { return BigDecimal.ZERO; } int signum = ((bytes[offset] & 0x80) == 0) ? -1 : 1; int scale; int index; int digitOffset; long multiplier = 100L; int begIndex = offset + 1; if (signum == 1) { scale = (byte) (((bytes[offset] & 0x7F) - 65) * -2); index = offset + length; digitOffset = POS_DIGIT_OFFSET; } else { scale = (byte) ((~bytes[offset] - 65 - 128) * -2); index = offset + length - (bytes[offset + length - 1] == NEG_TERMINAL_BYTE ? 1 : 0); digitOffset = -NEG_DIGIT_OFFSET; } length = index - offset; long l = signum * bytes[--index] - digitOffset; if (l % 10 == 0) { // trailing zero scale--; // drop trailing zero and compensate in the scale l /= 10; multiplier = 10; } // Use long arithmetic for as long as we can while (index > begIndex) { if (l >= MAX_LONG_FOR_DESERIALIZE || multiplier >= Long.MAX_VALUE / 100) { multiplier = LongMath.divide(multiplier, 100L, RoundingMode.UNNECESSARY); break; // Exit loop early so we don't overflow our multiplier } int digit100 = signum * bytes[--index] - digitOffset; l += digit100 * multiplier; multiplier = LongMath.checkedMultiply(multiplier, 100); } BigInteger bi; // If still more digits, switch to BigInteger arithmetic if (index > begIndex) { bi = BigInteger.valueOf(l); BigInteger biMultiplier = BigInteger.valueOf(multiplier).multiply(ONE_HUNDRED); do { int digit100 = signum * bytes[--index] - digitOffset; bi = bi.add(biMultiplier.multiply(BigInteger.valueOf(digit100))); biMultiplier = biMultiplier.multiply(ONE_HUNDRED); } while (index > begIndex); if (signum == -1) { bi = bi.negate(); } } else { bi = BigInteger.valueOf(l * signum); } // Update the scale based on the precision scale += (length - 2) * 2; BigDecimal v = new BigDecimal(bi, scale); return v; }