Example usage for java.lang System nanoTime

List of usage examples for java.lang System nanoTime

Introduction

In this page you can find the example usage for java.lang System nanoTime.

Prototype

@HotSpotIntrinsicCandidate
public static native long nanoTime();

Source Link

Document

Returns the current value of the running Java Virtual Machine's high-resolution time source, in nanoseconds.

Usage

From source file:org.messic.server.api.randomlists.AuthorRandomListPlugin.java

@Override
public RandomList getRandomList(User user) {
    // second list, getting all the songs of an author
    List<MDOAuthor> randomAuthorList = daoAuthor.getRandomAuthors(user.getLogin(), 1);
    if (randomAuthorList != null && randomAuthorList.size() > 0) {
        RandomList rl = new RandomList("RandomListName-Author", "RandomListTitle-Author");
        rl.addDetail(randomAuthorList.get(0).getName());
        Iterator<MDOAlbum> albumsit = randomAuthorList.get(0).getAlbums().iterator();
        while (albumsit.hasNext()) {
            MDOAlbum album = albumsit.next();
            List<MDOSong> songs = album.getSongs();
            for (int i = 0; i < songs.size() && rl.getSongs().size() < MAX_ELEMENTS; i++) {
                MDOSong mdoSong = songs.get(i);
                Song song = new Song(mdoSong, true, true);
                rl.addSong(song);/*  w w w. j ava2s  .c o m*/
            }
        }
        long seed = System.nanoTime();
        if (rl.getSongs() != null) {
            Collections.shuffle(rl.getSongs(), new Random(seed));
        }
        return rl;
    }
    return null;
}

From source file:com.gwac.job.FileTransferServiceImpl.java

public void startJob() {

    if (isBeiJingServer || isTestServer) {
        return;//from   w ww. j  ava2 s.c o  m
    }

    if (running == true) {
        log.debug("start job...");
        running = false;
    } else {
        log.warn("job is running, jump this scheduler.");
        return;
    }

    long startTime = System.nanoTime();
    //    transFile();
    long endTime = System.nanoTime();

    if (running == false) {
        running = true;
        log.debug("job is done.");
    }
    log.debug("job consume " + 1.0 * (endTime - startTime) / 1e9 + " seconds.");
}

From source file:org.messic.server.api.randomlists.DateRandomListPlugin.java

@Override
public RandomList getRandomList(User user) {
    // int year = Calendar.getInstance().get( Calendar.YEAR );
    int fromYear = daoAlbum.findOldestAlbum(user.getLogin()); // Util.randInt( 1920, year );
    int toYear = fromYear + 10;// Util.randInt( fromYear, year );
    List<MDOAlbum> albums = daoAlbum.findAlbumsBasedOnDate(user.getLogin(), fromYear, toYear);

    if (albums != null && albums.size() > 0) {
        RandomList rl = new RandomList("RandomListName-Date", "RandomListTitle-Date");
        rl.addDetail(fromYear + " - " + toYear);

        for (int i = 0; i < albums.size() && rl.getSongs().size() < MAX_ELEMENTS; i++) {
            List<MDOSong> songs = albums.get(i).getSongs();
            for (int j = 0; j < songs.size() && rl.getSongs().size() < MAX_ELEMENTS; j++) {
                MDOSong mdoSong = songs.get(j);
                Song song = new Song(mdoSong, true, true);
                rl.addSong(song);/*from  w  ww.j  ava 2s  .c  o  m*/
            }

        }

        long seed = System.nanoTime();
        if (rl.getSongs() != null) {
            Collections.shuffle(rl.getSongs(), new Random(seed));
        }
        return rl;
    }
    return null;
}

From source file:de.cebitec.mgx.seqstorage.ReaderFactoryTest.java

@Test
public void testGetCSQFReader() throws Exception {
    System.out.println("testGetCSQFReader");

    File temp = File.createTempFile("temp", Long.toString(System.nanoTime()));
    temp.delete();//  w  w  w.ja va2 s.c om
    temp.mkdirs();

    File f1 = copyTestData(FastaReader.class, "de/cebitec/mgx/seqstorage/3", temp, "3");
    File f2 = copyTestData(FastaReader.class, "de/cebitec/mgx/seqstorage/3.csq", temp, "3.csq");

    FactoryI<DNASequenceI> rf = new ReaderFactory();
    SeqReaderI<? extends DNASequenceI> reader = rf.<DNAQualitySequenceI>getReader(f1.getAbsolutePath());
    assertNotNull(reader);
    assertTrue(reader instanceof CSQFReader);

    f1.delete();
    f2.delete();
    temp.delete();
}

From source file:com.netflix.genie.core.jobs.workflow.impl.ApplicationTask.java

/**
 * {@inheritDoc}/*from   w  w  w . j  a va 2s  . co  m*/
 */
@Override
public void executeTask(@NotNull final Map<String, Object> context) throws GenieException, IOException {
    final long start = System.nanoTime();
    try {
        final JobExecutionEnvironment jobExecEnv = (JobExecutionEnvironment) context
                .get(JobConstants.JOB_EXECUTION_ENV_KEY);
        final String jobWorkingDirectory = jobExecEnv.getJobWorkingDir().getCanonicalPath();
        final String genieDir = jobWorkingDirectory + JobConstants.FILE_PATH_DELIMITER
                + JobConstants.GENIE_PATH_VAR;
        final Writer writer = (Writer) context.get(JobConstants.WRITER_KEY);
        log.info("Starting Application Task for job {}", jobExecEnv.getJobRequest().getId());

        if (jobExecEnv.getApplications() != null) {
            for (Application application : jobExecEnv.getApplications()) {
                final String applicationId = application.getId()
                        .orElseThrow(() -> new GeniePreconditionException("Application without id"));

                // Create the directory for this application under applications in the cwd
                createEntityInstanceDirectory(genieDir, applicationId, AdminResources.APPLICATION);

                // Create the config directory for this id
                createEntityInstanceConfigDirectory(genieDir, applicationId, AdminResources.APPLICATION);

                // Create the dependencies directory for this id
                createEntityInstanceDependenciesDirectory(genieDir, applicationId, AdminResources.APPLICATION);

                // Get the setup file if specified and add it as source command in launcher script
                final Optional<String> setupFile = application.getSetupFile();
                if (setupFile.isPresent()) {
                    final String applicationSetupFile = setupFile.get();
                    if (StringUtils.isNotBlank(applicationSetupFile)) {
                        final String localPath = super.buildLocalFilePath(jobWorkingDirectory, applicationId,
                                applicationSetupFile, FileType.SETUP, AdminResources.APPLICATION);
                        this.fts.getFile(applicationSetupFile, localPath);

                        super.generateSetupFileSourceSnippet(applicationId, "Application:", localPath, writer,
                                jobWorkingDirectory);
                    }
                }

                // Iterate over and get all dependencies
                for (final String dependencyFile : application.getDependencies()) {
                    final String localPath = super.buildLocalFilePath(jobWorkingDirectory, applicationId,
                            dependencyFile, FileType.DEPENDENCIES, AdminResources.APPLICATION);
                    fts.getFile(dependencyFile, localPath);
                }

                // Iterate over and get all configuration files
                for (final String configFile : application.getConfigs()) {
                    final String localPath = super.buildLocalFilePath(jobWorkingDirectory, applicationId,
                            configFile, FileType.CONFIG, AdminResources.APPLICATION);
                    fts.getFile(configFile, localPath);
                }
            }
        }
        log.info("Finished Application Task for job {}", jobExecEnv.getJobRequest().getId());
    } finally {
        final long finish = System.nanoTime();
        this.timer.record(finish - start, TimeUnit.NANOSECONDS);
    }
}

From source file:edu.umass.cs.reconfiguration.reconfigurationutils.ReconfigurationPacketDemultiplexer.java

@Override
public JSONObject processHeader(byte[] msg, NIOHeader header) {
    long t = System.nanoTime();
    int type;/*from w  w  w . j ava2  s.c o m*/
    JSONObject json = null;
    log.log(Level.FINEST, "{0} processHeader received message with header {1}", new Object[] { this, header });
    if (msg.length >= Integer.BYTES
            && ReconfigurationPacket.PacketType.intToType
                    .containsKey(type = ByteBuffer.wrap(msg, 0, 4).getInt())
            && JSONPacket.couldBeJSON(msg, Integer.BYTES)
            && type != PacketType.REPLICABLE_CLIENT_REQUEST.getInt()) {
        json = super.processHeader(msg, Integer.BYTES, header, true);
        if (json != null) {
            if (Util.oneIn(50))
                DelayProfiler.updateDelayNano("processHeader", t);
            return json;
        }
    } else if (!BYTEIFICATION && JSONPacket.couldBeJSON(msg)
            && (json = super.processHeader(msg, header, true)) != null) {
        return json;
    }
    // else prefix msg with addresses
    byte[] stamped = new byte[NIOHeader.BYTES + msg.length];
    ByteBuffer bbuf = ByteBuffer.wrap(stamped);
    bbuf.put(header.toBytes());
    bbuf.put(msg);
    if (Util.oneIn(50))
        DelayProfiler.updateDelayNano("processHeader", t);
    return new JSONMessenger.JSONObjectWrapper(stamped);
}

From source file:com.widowcrawler.terminator.parse.ParserTest.java

@Test(timeout = 1000)
public void parse_validRobotsTxtSmall_parsesFile() throws Exception {
    InputStream inputStream = new FileInputStream("src/test/resources/example_robots_small.txt");

    Parser parser = new Parser(inputStream);

    long start = System.nanoTime();
    RobotsTxt robotsTxt = parser.parse();
    long duration = System.nanoTime() - start;

    System.out.println("Duration: " + duration);

    robotsTxt.getRuleSets().forEach((userAgent, rules) -> {
        System.out.println("User-agent: " + userAgent);

        rules.forEach(rule -> System.out.println(rule.getRuleType().toString() + ": " + rule.getPathMatch()));
    });/* w ww . j a  v  a 2s. co m*/

    System.out.println("\n\n");

    robotsTxt.getSiteMapRefs().forEach(ref -> System.out.println("Sitemap: " + ref));
}

From source file:de.cosmocode.palava.store.AbstractStoreTest.java

/**
 * Tests {@link Store#create(InputStream)} with a custom {@link IdGenerator}.
 * //from  w  w  w .  j  a va  2  s.c  o  m
 * @throws IOException should not happen
 */
@Test
public void createCustomGenerator() throws IOException {
    final String identifier = Long.toBinaryString(System.nanoTime());
    final IdGenerator generator = EasyMock.createMock("identifier", IdGenerator.class);
    EasyMock.expect(generator.generate()).andReturn(identifier);
    EasyMock.replay(generator);
    final Store unit = unitWithGenerator(generator);
    final InputStream stream = getClass().getClassLoader().getResourceAsStream("willi.png");
    Assert.assertNotNull(stream);
    final String generatedIdentifier = unit.create(stream);
    Assert.assertEquals(identifier, generatedIdentifier);
    EasyMock.verify(generator);
}

From source file:eu.planets_project.pp.plato.services.characterisation.xcl.XclPropertiesExplorer.java

private String makeTempDir() {
    String tempDir = OS.getTmpPath() + "xclexplorer" + System.nanoTime() + "/";
    new File(tempDir).mkdir();
    return tempDir;
}

From source file:com.iflytek.edu.cloud.frame.web.filter.ServiceMetricsFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    //HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    StatHttpServletResponseWrapper responseWrapper = new StatHttpServletResponseWrapper(httpResponse);

    final String method = request.getParameter(Constants.SYS_PARAM_KEY_METHOD);
    final String appkey = request.getParameter(Constants.SYS_PARAM_KEY_APPKEY);
    long startNano = System.nanoTime();
    long startMillis = System.currentTimeMillis();

    serviceAppStat.beforeInvoke();/* ww  w  . j  a v a  2  s . c o  m*/

    ServiceMethodStat methodStat = serviceAppStat.getMethodStat(appkey, method);
    if (methodStat == null) {
        methodStat = serviceAppStat.getMethodStat(appkey, method);
    }

    if (methodStat != null) {
        methodStat.beforeInvoke(startMillis);
    }

    Throwable error = null;
    try {
        chain.doFilter(request, responseWrapper);
    } catch (IOException e) {
        error = e;
        throw e;
    } catch (ServletException e) {
        error = e;
        throw e;
    } catch (RuntimeException e) {
        error = e;
        throw e;
    } catch (Error e) {
        error = e;
        throw e;
    } finally {
        long endNano = System.nanoTime();
        long nanos = endNano - startNano;
        serviceAppStat.afterInvoke(error, nanos);

        if (methodStat != null) {
            methodStat.afterInvoke(error, nanos);
            request.setAttribute(SERVICE_EXEC_TIME, nanos / (1000 * 1000));
        }
    }
}