Java Code Examples for java.lang.management.ThreadMXBean#getCurrentThreadCpuTime()

The following examples show how to use java.lang.management.ThreadMXBean#getCurrentThreadCpuTime() . 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: OperatorProfiler.java    From rheem with Apache License 2.0 6 votes vote down vote up
/**
 * Executes and profiles the profiling task. Requires that this instance is prepared.
 */
public Result run() {
    final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    threadMXBean.setThreadCpuTimeEnabled(true);
    ProfilingUtils.sleep(1000);
    long startCpuTime = threadMXBean.getCurrentThreadCpuTime();
    final long outputCardinality = this.executeOperator();
    long endCpuTime = threadMXBean.getCurrentThreadCpuTime();

    long cpuCycles = this.calculateCpuCycles(startCpuTime, endCpuTime);
    return new Result(
            this.inputCardinalities,
            outputCardinality,
            this.provideDiskBytes(),
            this.provideNetworkBytes(),
            cpuCycles
    );
}
 
Example 2
Source File: OdaTiming.java    From OpenDA with GNU Lesser General Public License v3.0 5 votes vote down vote up
/** Get CPU time in nanoseconds. */

private long getCpuTime( ) {
	ThreadMXBean bean;
	try {
		bean = ManagementFactory.getThreadMXBean( );
	} catch (Error e) {
		// not supported (happens in the by means of IKVM converted version (.net)
		return 0L;
	}
	return bean.isCurrentThreadCpuTimeSupported( ) ?
        bean.getCurrentThreadCpuTime( ) : 0L;
}
 
Example 3
Source File: Timing.java    From kanzi with Apache License 2.0 5 votes vote down vote up
public long getSystemTime()
{
   ThreadMXBean bean = ManagementFactory.getThreadMXBean();

   return bean.isCurrentThreadCpuTimeSupported() ? 
      (bean.getCurrentThreadCpuTime() - bean.getCurrentThreadUserTime()) : 0L;
}
 
Example 4
Source File: TraceThreadStatsIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public void transactionMarker() throws Exception {
    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    long start = threadBean.getCurrentThreadCpuTime();
    while (threadBean.getCurrentThreadCpuTime() - start < MILLISECONDS.toNanos(10)) {
        for (int i = 0; i < 1000; i++) {
            Math.pow(i, i);
        }
    }
}
 
Example 5
Source File: YFCC100MExample.java    From multimedia-indexing with Apache License 2.0 4 votes vote down vote up
/** Get CPU time in milliseconds. */
public static long getCpuTime() {
	ThreadMXBean bean = ManagementFactory.getThreadMXBean();
	return bean.isCurrentThreadCpuTimeSupported() ? (long) ((double) bean.getCurrentThreadCpuTime() / 1000000.0)
			: 0L;
}
 
Example 6
Source File: TestTenantContainer.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
public long getCpuTime () {
    ThreadMXBean bean = ManagementFactory.getThreadMXBean();
    return bean.isCurrentThreadCpuTimeSupported() ? bean
            .getCurrentThreadCpuTime() : 0L;
}
 
Example 7
Source File: Timing.java    From kanzi with Apache License 2.0 4 votes vote down vote up
public long getCpuTime()
{
   ThreadMXBean bean = ManagementFactory.getThreadMXBean();
   return bean.isCurrentThreadCpuTimeSupported() ? bean.getCurrentThreadCpuTime() : 0L;
}
 
Example 8
Source File: TimeMagicCommand.java    From beakerx with Apache License 2.0 4 votes vote down vote up
public MagicCommandOutput time(String codeToExecute, Message message, int executionCount, boolean showResult) {
  CompletableFuture<TimeMeasureData> compileTime = new CompletableFuture<>();

  ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
  long currentThreadId = Thread.currentThread().getId();

  Long startWallTime = System.nanoTime();
  Long startCpuTotalTime = threadMXBean.getCurrentThreadCpuTime();
  Long startUserTime = threadMXBean.getCurrentThreadUserTime();

  SimpleEvaluationObject simpleEvaluationObject = createSimpleEvaluationObject(codeToExecute, kernel, message, executionCount);
  if (!showResult) {
    simpleEvaluationObject.noResult();
  }

  TryResult either = kernel.executeCode(codeToExecute, simpleEvaluationObject);

  Long endWallTime = System.nanoTime();
  Long endCpuTotalTime = threadMXBean.getThreadCpuTime(currentThreadId);
  Long endUserTime = threadMXBean.getThreadUserTime(currentThreadId);

  compileTime.complete(new TimeMeasureData(endCpuTotalTime - startCpuTotalTime,
          endUserTime - startUserTime,
          endWallTime - startWallTime));
  String messageInfo = "CPU times: user %s, sys: %s, total: %s \nWall Time: %s\n";

  try {
    TimeMeasureData timeMeasuredData = compileTime.get();

    return new MagicCommandOutput(MagicCommandOutput.Status.OK,
            String.format(messageInfo,
                    format(timeMeasuredData.getCpuUserTime()),
                    format(timeMeasuredData.getCpuTotalTime() - timeMeasuredData.getCpuUserTime()),
                    format(timeMeasuredData.getCpuTotalTime()),
                    format(timeMeasuredData.getWallTime())),
            either,
            simpleEvaluationObject);

  } catch (InterruptedException | ExecutionException e) {
    return new MagicCommandOutput(MagicCommandOutput.Status.ERROR, "There occurs problem during measuring time for your statement.");
  }
}
 
Example 9
Source File: KillAllChildProcessTaskTest.java    From gocd with Apache License 2.0 4 votes vote down vote up
public long getSystemTime() {
    ThreadMXBean bean = ManagementFactory.getThreadMXBean();
    return bean.isCurrentThreadCpuTimeSupported() ?
            (bean.getCurrentThreadCpuTime() - bean.getCurrentThreadUserTime()) : 0L;
}
 
Example 10
Source File: KillAllChildProcessTaskBuilderTest.java    From gocd with Apache License 2.0 4 votes vote down vote up
public long getSystemTime() {
    ThreadMXBean bean = ManagementFactory.getThreadMXBean();
    return bean.isCurrentThreadCpuTimeSupported() ?
            (bean.getCurrentThreadCpuTime() - bean.getCurrentThreadUserTime()) : 0L;
}
 
Example 11
Source File: Timing.java    From oopsla15-artifact with Eclipse Public License 1.0 4 votes vote down vote up
public static long getCpuTime( ) {
    ThreadMXBean bean = ManagementFactory.getThreadMXBean( );
    return bean.isCurrentThreadCpuTimeSupported( ) ?
        bean.getCurrentThreadCpuTime( ) : 0L;
}
 
Example 12
Source File: EcdsaTest.java    From wycheproof with Apache License 2.0 4 votes vote down vote up
/**
 * Tests for a potential timing attack. This test checks if there is a correlation between the
 * timing of signature generation and the size of the one-time key k. This is for example the case
 * if a double and add method is used for the point multiplication. The test fails if such a
 * correlation can be shown with high confidence. Further analysis will be necessary to determine
 * how easy it is to exploit the bias in a timing attack.
 */
// TODO(bleichen): Determine if there are exploitable providers.
//
// SunEC currently fails this test. Since ECDSA typically is used with EC groups whose order
// is 224 bits or larger, it is unclear whether the same attacks that apply to DSA are practical.
//
// The ECDSA implementation in BouncyCastle leaks information about k through timing too.
// The test has not been optimized to detect this bias. It would require about 5'000'000 samples,
// which is too much for a simple unit test.
//
// BouncyCastle uses FixedPointCombMultiplier for ECDSA. This is a method using
// precomputation. The implementation is not constant time, since the precomputation table
// contains the point at infinity and adding this point is faster than ordinary point additions.
// The timing leak only has a small correlation to the size of k and at the moment it is is very
// unclear if the can be exploited. (Randomizing the precomputation table by adding the same
// random point to each element in the table and precomputing the necessary offset to undo the
// precomputation seems much easier than analyzing this.)
public void testTiming(String algorithm, String curve, ECParameterSpec ecParams)
    throws Exception {
  ThreadMXBean bean = ManagementFactory.getThreadMXBean();
  if (!bean.isCurrentThreadCpuTimeSupported()) {
    System.out.println("getCurrentThreadCpuTime is not supported. Skipping");
    return;
  }
  KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
  try {
    keyGen.initialize(ecParams);
  } catch (InvalidAlgorithmParameterException ex) {
    System.out.println("This provider does not support curve:" + curve);
    return;
  }
  KeyPair keyPair = keyGen.generateKeyPair();
  ECPrivateKey priv = (ECPrivateKey) keyPair.getPrivate();

  String message = "Hello";
  String hashAlgorithm = getHashAlgorithm(algorithm);
  byte[] messageBytes = message.getBytes("UTF-8");
  byte[] digest = MessageDigest.getInstance(hashAlgorithm).digest(messageBytes);
  BigInteger h = new BigInteger(1, digest);
  Signature signer = Signature.getInstance(algorithm);
  signer.initSign(priv);
  // The number of samples used for the test. This number is a bit low.
  // I.e. it just barely detects that SunEC leaks information about the size of k.
  int samples = 50000;
  long[] timing = new long[samples];
  BigInteger[] k = new BigInteger[samples];
  for (int i = 0; i < samples; i++) {
    long start = bean.getCurrentThreadCpuTime();
    signer.update(messageBytes);
    byte[] signature = signer.sign();
    timing[i] = bean.getCurrentThreadCpuTime() - start;
    k[i] = extractK(signature, h, priv);
  }
  long[] sorted = Arrays.copyOf(timing, timing.length);
  Arrays.sort(sorted);
  double n = priv.getParams().getOrder().doubleValue();
  double expectedAverage = n / 2;
  double maxSigma = 0;
  System.out.println("testTiming algorithm:" + algorithm);
  for (int idx = samples - 1; idx > 10; idx /= 2) {
    long cutoff = sorted[idx];
    int count = 0;
    BigInteger total = BigInteger.ZERO;
    for (int i = 0; i < samples; i++) {
      if (timing[i] <= cutoff) {
        total = total.add(k[i]);
        count += 1;
      }
    }
    double expectedStdDev = n / Math.sqrt(12 * count);
    double average = total.doubleValue() / count;
    // Number of standard deviations that the average is away from
    // the expected value:
    double sigmas = Math.abs(expectedAverage - average) / expectedStdDev;
    if (sigmas > maxSigma) {
      maxSigma = sigmas;
    }
    System.out.println(
        "count:"
            + count
            + " cutoff:"
            + cutoff
            + " relative average:"
            + (average / expectedAverage)
            + " sigmas:"
            + sigmas);
  }
  // Checks if the signatures with a small timing have a biased k.
  // We use 7 standard deviations, so that the probability of a false positive is smaller
  // than 10^{-10}.
  if (maxSigma >= 7) {
    fail("Signatures with short timing have a biased k");
  }
}
 
Example 13
Source File: GreedyScorer.java    From blip with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Evaluate the parent sets of the variable in the available time, following an heuristic ordering.
 */
@Override
public void run() {

    ThreadMXBean bean = ManagementFactory.getThreadMXBean();
    double start = bean.getCurrentThreadCpuTime();
    double elapsed = 0;

    prepare();

    if (verbose > 2) {
        log.info(
                String.format("Starting with: %d, max time: %.2f", n,
                max_exec_time));
    }

    // int arity = dat.l_n_arity[n];

    // Initialize everything
    closed = new TCustomHashSet<int[]>(new ArrayHashingStrategy()); // Parent set already seen
    open = new TreeSet<ParentSetEntry>(); // Parent set to evaluate

    // Compute one-scores
    for (int p = 0; p < dat.n_var; p++) {

        if (p == n) {
            continue;
        }

        double sk;

        sk = oneScores.get(p);

        addScore(p, sk);

        addParentSetToEvaluate(new int[] { p}, sk, null);
    }

    if (max_exec_time == 0) {
        max_exec_time = Integer.MAX_VALUE;
    }

    // Consider all the parent set for evaluation!
    while (!open.isEmpty() && (elapsed < max_exec_time)) {

        ParentSetEntry pset = open.pollLast();

        if (pset == null) {
            continue;
        }

        for (int p2 = 0; (p2 < dat.n_var) && (elapsed < max_exec_time); p2++) {

            if (p2 == n) {
                continue;
            }

            evaluteParentSet(n, pset.s, p2, pset.p_values);

            elapsed = (bean.getCurrentThreadCpuTime() - start)
                    / 1000000000;
        }
    }

    if (verbose > 2) {
        log.info(
                String.format(
                        "ending with: %d, elapsed: %.2f, num evaluated %d",
                        n, elapsed, score.numEvaluated));
    }

    // synchronized (scorer) {
    if (verbose > 0) {
        System.out.println("... finishing " + n);
    }

    conclude();
}
 
Example 14
Source File: AdvK2.java    From blip with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void run() {

            if (verbose > 2) {
                log.info(
                        String.format("Starting with max time: %.2f",
                        max_exec_time));
            }

            ThreadMXBean bean = ManagementFactory.getThreadMXBean();
            double start = bean.getCurrentThreadCpuTime();
            double elapsed = 0;

            // App ord
            TIntArrayList ord = new TIntArrayList();

            for (int n1 = 0; n1 < dat.n_var; n1++) {
                ord.add(n1);
            }

            boolean cnt = true;

            while (cnt) {

                ord.shuffle(rand);

                for (int n = 0; (n < dat.n_var) && cnt; n++) {
                    findBestParentSet(ord, n);

                    elapsed = (bean.getCurrentThreadCpuTime() - start)
                            / 1000000000;
                    cnt = elapsed < max_exec_time;
                }
            }

            if (verbose > 2) {
                log.info(
                        String.format(
                                "ending with: elapsed: %.2f, num evaluated %d",
                                elapsed, score.numEvaluated));
            }
        }
 
Example 15
Source File: GeneralUtils.java    From ade with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Returns the difference between the current thread's CPU time and user time.
 * 
 * @return the current thread's system time, or 0 if CPU time is not supported
 *     for the current thread
 */
public static long getSystemTime() {
    final ThreadMXBean bean = ManagementFactory.getThreadMXBean();
    final long systemTime = bean.getCurrentThreadCpuTime() - bean.getCurrentThreadUserTime();
    return bean.isCurrentThreadCpuTimeSupported() ? systemTime : 0L;
}
 
Example 16
Source File: GeneralUtils.java    From ade with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Returns the current thread's CPU time.
 * 
 * @return the current thread's CPU time, or 0 if CPU time is not supported
 *     for the current thread
 */
public static long getCpuTime() {
    final ThreadMXBean bean = ManagementFactory.getThreadMXBean();
    return bean.isCurrentThreadCpuTimeSupported() ? bean.getCurrentThreadCpuTime() : 0L;
}
 
Example 17
Source File: SeqAdvScorer.java    From blip with GNU Lesser General Public License v3.0 2 votes vote down vote up
/**
 * Evaluate the parent sets of the variable in the available time, following an heuristic ordering.
 */
@Override
public void run() {

    if (verbose > 2) {
        log.info(
                String.format("Starting with: %d, max time: %.2f", n,
                max_exec_time));
    }

    ThreadMXBean bean = ManagementFactory.getThreadMXBean();
    double start = bean.getCurrentThreadCpuTime();
    double elapsed = 0;

    int pset_size = 2;

    MutualInformation mi = new MutualInformation(dat);
    LogLikelihood ll = new LogLikelihood(dat);
    double ll_n = ll.computeLL(n);

    double[] w = new double[n_var];

    for (int i = 0; i < n_var; i++) {
        if (i == n) {
            continue;
        }

        double ll_i = ll.computeLL(n, i);

        double m = mi.computeMi(n, i) * dat.n_datapoints;
        double l = max(ll_n, ll.computeLL(i));

        // double l = - (ll_n -ll.go(n, thread)) / dat.n_datapoints;

        w[i] = m - l;
    }

    while (elapsed < max_exec_time) {

        int[] pset = new int[pset_size];

        for (int i = 0; i < pset_size; i++) {
            pset[i] = i;
        }

        // System.out.printf("%d - %d\n", dat.n_var, n);

        boolean cnt = true;

        while (cnt && (elapsed < max_exec_time)) {

            // System.out.println(Arrays.toString(set));

            if (Arrays.binarySearch(pset, n) < 0) {

                double sk = score.computeScore(n, pset);

                double bestScore;

                bestScore = voidSk;

                if (sk > bestScore) {
                    addScore(pset, sk);
                }
            }

            cnt = incrementPset(pset, pset.length - 1, dat.n_var);

            elapsed = (bean.getCurrentThreadCpuTime() - start)
                    / 1000000000;
        }

        pset_size++;

        if (max_pset_size > 0 && pset_size >= max_pset_size) {
            break;
        }

    }

    if (verbose > 2) {
        log.info(
                String.format(
                        "ending with: %d, elapsed: %.2f, num evaluated %d",
                        n, elapsed, score.numEvaluated));
    }

    conclude();

}