System.nanoTime X System.currentTimeMillis

Hi,
i`ve been trying to make some measurments in my app without the use of any other specializes tool like optimizer, so i`m trying to hear as many opinios i can (as someones my noticed, i`ve posted some similar questions on this topic).
I did make a test in my windows XP and got the precision of System.currentTimeMillis() around 15 ms, but i need a more accurate measurment. I know the j2se 1.5 has a System.nanoTime() function wich gives nanoseconds measurment.
However, before i download, install and reconfigure my system`, i`d like to hear some opinions.
If i use System.nanoTime(), i`ll get the time in nanoseconds, but will the ERROR average (or the accuracy) be the same as with System.currentTimeMillis() ???
Cause if i have a method that takes 1500 ms (MILIseconds) or 1500000 ns (NANOseconds) and the precision o my system still be 15ms (MILIseconds) i`d wouldn`t be helpfull, right!
So, can i get some opinions?!
Thanks,
ltcmelo

>
well... it was my understanding that Windows has the
capability, but you have to enable it somehow, cuz
it's not enabled by default. That could be wrong, as
I'm not a Windows programmer. But I've never seen
Java give better then 10 ms precision on any Windows
system.Not that I know about..
From a December 1997 MSJ Article "Under the Hood"....
Before I get to the benchmarking code and, more importantly, the results, let me say a few things about my efforts to make the timings reliable. I used the QueryPerformanceCounter API, which provides timings at the microsecond level. According to the QueryPerformanceFrequency API, the performance counter increments 1.19 million times a second, a number that corresponds to one of the traditional timers found on x86-based systems. To prevent the numbers from being skewed by too few samples, I executed the APIs 50,000 times in a loop.
Looking at the code I didn't seen anything that suggested that it was being enabled.
The API is available back to 95 and NT.
MIght be something newer but I use a 2000 version of MSDN (they switched formats after that and made it unusable.)

Similar Messages

  • Measure how long a code take to executes with System.currentTimeMillis()

    hi,
    I have this piece of code
    start = System.currentTimeMillis();
    // other statetments here, that needed to be measured in time
    end = System.currentTimeMillis();
    System.out.println(end - start + " msec to run");is that the right way to do it?
    there is also a static method from System class nanoTime(), what is the different? (the api doc is a little difficult to understand cause my english is bad)
    with currentTimeMillis() as solution I get one time 16 ms and another time 32 ms for the same piece of code,
    and when I put a for loop (like 16 times doing the same thing) around the statements that I want to test, there where times that I get runtime as 0 ms,

    That works, but you'll want to
    * Make sure that what's between the two curentTimeMillis calls takes at least a second. (100 times the resolution of most system clocks)
    * Run the entire thing in a loop a hundreds or thousands of times and look at at least the average, and possibly the min, max, mean, and std dev.
    * Understand that your CPU is doing other things besides running your Java program, and even when running your Java program, the VM is doing other things besides executing those statements, so that the time is likely to vary from one execution to the next.
    * Understand that hotspot interprets code for a while, and then compiles it, so that the first 10,000 iterations may take longer than the next 100,000.

  • Converting value from System.currentTimeMillis() to readable format

    hi
    i have in database coumn with values that were stored as result of executing System.currentTimeMillis() in java (=“the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC). i need to convert these values to some human readable format.
    i am able to get year, month and day from these values(value_date) in format "dd/mm/yyyy" but i need hours, minutes and seconds as well.
    select i have for getting years, months and days:
    select (
    extract (day FROM (to_date('01/01/1970 00:00:00000','mm/dd/yyyy hh24:mi:sssss') + value_date/1000/86400))
    || '/'||
    extract (month from (to_date('01/01/1970 00:00:00000','mm/dd/yyyy hh24:mi:sssss') + value_date/1000/86400))
    ||'/'||
    extract (year FROM (to_date('01/01/1970 00:00:00000','mm/dd/yyyy hh24:mi:sssss') + value_date/1000/86400))
    FROM some_table;
    please advice how to improve this select to get something like "dd/mm/yyyy hh:mm:ss"
    thanks

    Note that the result with to_char might still not be what you expect (due to timezone and/or DTS):
    SQL>  CREATE OR REPLACE FUNCTION currenttimemillis
       RETURN NUMBER
    IS
       LANGUAGE JAVA
       NAME 'java.lang.System.currentTimeMillis() return java.lang.long';
    Function created.
    SQL>  select to_char(sysdate, 'dd.mm.rrrr hh24:mi:ss') dt,
           to_char(date '1970-01-01' + currentTimeMillis/(1000*24*60*60),'dd.mm.rrrr hh24:mi:ss') dt2
      from dual
    DT                  DT2               
    04.06.2009 16:44:09 04.06.2009 14:44:09

  • System.currentTimeMillis() problem in Solaris

    hi all
    I have one problem, I have one aplicantion transactional development in java runing in win Nt that up 3 console different + 1 registry console. I have that save the transaction's date in the DB when begin transaction and end transaction. In win NT with Timestamp(System.currentTimeMillis()) is OK. Now in Solaris when up the 3 console, in one, Timestamp(System.currentTimeMillis()) show me the correct time(the time set in the server), but in other console show me other time different (six hour +) and I don't know where takes out this time. I saw the server's timezone and it's ok, and I do in one console >date show me the correct time.
    Anyone help me?
    More information:
    Solaris 8

    Huh?
    currentTimeMillis() returns a number so I can only suppose that on one machine the number is significantly different than on another.
    That means that the times on the machines (nothing to do with java) are different.
    If however you are using Date() to create and display a time, then it means the timezones are different (again nothing to do with java.)

  • Question of System.currentTimeMillis();

    Hi there,
    I got some problem in method "System.currentTimeMillis()" .
    The part of my function is:
         long c= System.currentTimeMillis();
         System.out.println("before time="+c);
              some codes here
    try{new Thread().sleep(1000);}catch(Exception e){} //sleep for additional 1 second
         long b= System.currentTimeMillis();
         System.out.println("after time="+b);
         c=c-b;
         System.out.println("run time="+c);
    the output is:
         before time=1001526336640
         after time= 1001526345985
         run time= -9345
    Couple things I could understand:
    1. b and c are long. in Java they are 8 bytes. in C++ LIMITS.H, long is 4 bytes "#define ULONG_MAX 0xffffffffUL /* maximum unsigned long value */"
    But why time value shows that huge number?
    2. It is strange to get small time after running, the currentTimeMillis() return the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.
    It took me whole day but I couldn't get answer yet. Do you have some idea?
    Thanks

    Im not quite sure what your asking here ?????
    One thing I would like to point out is that you have youre vars a bit mixed in the subtraction
    long b= System.currentTimeMillis();
    System.out.println("after time="+b);
    c=c-b;
    System.out.println("run time="+c);should be
    c= b-c which would equal:9345
    aproximately 9 seconds...
    the currentTimeMillis() return the difference, >>measured in milliseconds, between the current time >>and midnight, January 1, 1970 UTC, Im not too sure this is correct the way you have it stated....
    Its better stated that currentTimeMillis() returns the number of milliseconds that have elapsed, at this current time, since midnight, January 1, 1970 UTC, which is a rather large number..Do the math if youd like.....
    A time yesterday will be smaller than a time today...
    Unfortunately you will need to state your question a bit better in order to get an adequate answer, Please do so and Im sure youll get some answers...

  • Nokia 6030 and System.currentTimeMillis

    Hi
    I'm developing my game for J2ME phones. It works well on a lot of devices. Today I got Nokia 6030 (S40 2nd Edition) and tested my game on this phone. It very strange! Timer works veeeery fast. I made small debug on screen. I made drawString System.currentTimeMillis() and I saw that time goes very fast. On all phones System.currentTimeMillis() increases 1000 per second. On 6030 System.currentTimeMillis() increases 1000000 (or more) per second. Why?!?! On emulator of Nokia 6030 it works well (1000 per second). It very strange. I tested this program on a lot of devices and everywhere it worked well.
    Help me, please...
    MDW

    could be a bug, someone accidentally putting tree zero to much in their code...

  • System.currentTimeMillis() returns time in UTC or not??????

    Hello Friends,
    I want to know that "System.currentTimeMillis()" returns time in UTC or Current Local time
    ie suppose i set my TimeZone (GMT+ 2)
    then statement gives me value in milliseconds by adding 2 hours to the GMT(Is this value should consider as UTC time or we have to subtract and add offset value according to the timezone.
    If time value return by statement is in local time and this is not UTC then is there is any provision in Java to convert local time into UTC time ??
    Regards
    Gaurav

    ejp wrote:
    It returns 'the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.'.Which, of course, as I have tried to explain to the OP (but seemingly not very well) that the "current time" referenced must also be the "current time" in UTC. If the starting point is UTC the ending point is UTC (otherwise it doesn't make any sense to measure it that way). I also attempted to tell him that, when he outputs a String representation of that time (i.e. toString or with a DateFormat Object) that the time he sees will be the time according to the TimeZone set in the DateFormat object, or the local timezone when using toString. But, as mentioned, Date objects (and so, essentially, the long value) is always UTC (relevant to the starting point, of course).
    A quote from the Date Class
    Although the Date class is intended to reflect coordinated universal time (UTC), it may not do so exactly, depending on the host environment of the Java Virtual Machine.which I take to mean that Date is always UTC in so far as the host environment is capable of it.

  • System.currentTimeMillis() going backwards!!!

    Hi,
    The following program runs a loop, each iteration measuring the time, and ensuring the new time is later than the last measured time.
    I run it like this:
    java -cp . Test 500 1
    My JVM is this:
    ahl84:/nfs/ahl16/users/is/djepson/work/backwards $ java -version
    java version "1.3.1.01-release"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.3.1.01-release-010816-12:37)
    Java HotSpot(TM) Server VM (build 1.3.1 1.3.1.01-release-010816-13:34-PA_RISC2.0 PA2.0, mixed mode)
    On one of our production machines, this program actually reaches the ERROR line - i.e. time is SEEN to go backwards.
    The problem also happens (although less frequently if I use a 0 for the sleep value - i.e. I am not forcing rescheduling on the main thread.
    Please, anyone any ideas???
    The machine in question has 2 CPUs if thats any help, but I can run it on other multi-CPU machines, seemingly without problem.
    public class Test
       public static void main( String[] args )
          for ( int i = 0; i < args.length; i++ )
             System.out.println( "arg[" + i + "]=[" + args[i] + "]" );
          if ( args.length != 2 )
             System.out.println( "Usage:" );
             System.out.println( "java -cp . Test [iterations] [delay (ms)]" );
          else
             Integer iterations = Integer.valueOf( args[0] );
             Integer delay = Integer.valueOf( args[1] );
             Test t = new Test( iterations.intValue(), delay.intValue() );
             t.go();
       public Test( int iterations, int delay )
          _iterations = iterations;
          _delay = delay;
          _errors = 0;
          _lastTime = System.currentTimeMillis();
       public void go()
          System.out.println( "START : Iterations=[" + _iterations + "], delay=[" + _delay + "], time=[" + _lastTime + "]" );
          for ( int i = 0; i < _iterations; i++ )
             long now = System.currentTimeMillis();
             if ( now < _lastTime )
                System.out.println( "Time sequence ERROR, i=[" + i + "], last=[" + _lastTime + "], now=[" + now + "]" );
                _errors++;
             else
                System.out.println( "Time sequence OK,    i=[" + i + "], last=[" + _lastTime + "], now=[" + now + "]" );
                _lastTime = now;
             if ( _delay > 0 )
                try
                   Thread.currentThread().sleep( _delay );
                catch ( InterruptedException e )
                   e.printStackTrace();
          System.out.println( "FINISH : Time=[" + _lastTime + "] errors=[ " + _errors + " / " + _iterations + " (" + ((float)_errors / (float)_iterations * 100) + "%) ]" );
       long _lastTime;
       int  _iterations;
       int  _errors;
       int  _delay;

    I think You may be running into an os/hardware problem. The
    System.currentTimeMillis() returns the number of milli secs since
    sometime in 1970. However the actual resolution of it depends on the operating system and hardware. Its possible that the thread is being
    allcoated to different procs on your machine (after sleeps especially
    and sometimes anyway) and the OS call used by java returns different
    values.
    for some reason I have a hunch that this isn't a java problem as such.
    maybe os/ maybe hardware/ maybe interation of java with both.
    try forcing the VM to run on one processor only.
    matfud

  • Help with code for System.currentTimeMillis()

    I need to time how long it takes to do various sorts (selection sort, insertion sort) and was instructed to use System.currentTimeMillis() to accomplish this. Please take a look at the code below and let me know what is wrong. I can get the file to complile but it does not record the time it takes to run the sorts. I'm pretty sure my error is in the below section of code. In order to save space, I've only pasted the snippit of code for this particular function. Let me know if I need to paste more code. Thanks in advance.
    case 5:
                             System.out.print("Enter the value to look for: ");
         val = scan.nextInt();
         time1 = System.currentTimeMillis();
         loc = list.linearSearch(val);
         time2 = System.currentTimeMillis();
                             totalTime = time1 - time2;
                             System.out.println("Total time for this search is: " + totalTime);
         if (loc != -1)
                                  System.out.println("Found at location " + loc);
         else
                                  System.out.println("Not in list");
         break;
                             

    It could be that it isn't actually doing anything
    though. Either because the data is poorly choosen or
    because it isn't actually sorting due to a bug.The name of the method being timed is "linearSearch". That's a really poor name for a method that is supposed to be sorting. But from other aspects of the code I would guess that it is doing a linear search of an array, looking for a particular integer. Even if the integer isn't in the array, comparing 20,000 integers is a trivial exercise.
    People don't realize just how long a millisecond is for a computer. If you have a 1 GB processor (not uncommon these days) then you can do one billion (one thousand million) operations per second. That's one million operations per millisecond. So chances are, even realizing that there's a whole lot of overhead in a high-level language, the OP's code runs in less than 1 millisecond.

  • System.currentTimeMillis() not accurate on Windows ?

    Hi,
    JVM : 1.4.2_03-b02
    OS : Windows XP
    processor : XEON 2.4 GHz
    Following test fails with 62.5 error percentage.
    Is it due to windows failing to give time on a millisecond level ?
    Or is there another reason ?
      public void testSleep() throws Exception {
        int total = 1000;
        int errors = 0;
        for ( int j = 0; j < total; j++ ) {
          long start = System.currentTimeMillis();
          Thread.sleep(5);
          long end = System.currentTimeMillis();
          if ( end < start+5 ) {
            errors++;
        Float errorPercentage = new Float( errors*(float)100/total );
        assertEquals( new Float(0), errorPercentage );
      }Regards, Tom.

    The millisecond level of precision is only a possibility provided by the API, the OS does not forcibly provide it.
    But Thread.sleep will not be absolutely precise, it is the most likely culprit.

  • Weblogic 9.2 , JDK 1.5 and System.currentTimeMillis()

    Hi
    I am using Weblogic 9.2 and JDK 1.5
    In my application I have System.currentTimeMillis().
    But when I use WL9.2 the time is getting 15 minues faster.
    For eg. if system time is 10.00 am , in WL9.2 it reads as 10.15 am ,so around 15 minutes faster
    Any thought s o nthis issue..
    How can configure this?
    Thanks in advance
    -Binu

    This is not a certified combination -- it has probably never ever been tested is my guess as 9.0.3 was released back in 2001(2?) (can't recall exactly) which was well before JDK5 was released.
    You can generally change the JDK used to run an OC4J instance by changing the JDK path in the opmn.xml file.
    But please note that this is not supported, almost certainly not tested (at least by us) so the outcome is not clear.
    The first release we support JDK5 with is 10.1.3 -- is doing an upgrade a possibililty for you?
    -steve-

  • System.currentTimeMillis() and Date()

    Hi,everybody
    What is the difference beetween System.currentTimeMillis() and Date()?
    Regards,
    Michael

    Michael,
    System.currentTimeMillis()  -- current date represented as number of milliseconds after/before Jan 1, 1970
    java.util.Date -- object that encapsulates date, when constructor called without arguments then it's current date. Note that almost all methods of this class are deprecated while it was designed only for Grigorian calendar. To get specific day/month/year from java.util.Date use java.util.Calendar.
    Valery Silaev
    SaM Solutions
    http://www.sam-solutions.net

  • Difference between using new Date() and new Date(System.currentTimeMillis()

    Hi All,
    I have seen many open source api's where they are updating dates with the following code
    new Date(System.currentTimeMillis())
    when i print the new Date() it prints the same
    what is the difference between using new Date() and new Date(System.currentTimeMillis()) ??
    Thanks,
    J.Kathir

    when i print the new Date() it prints the same
    It does because of backward compatability. This constructor exists in version 1.3.1 but not in newer versions.Really ? Please point me to where you read that.
    API doc 1.5 : new Date() (still there, not even deprecated)
    A quick look at the code for this constructor:    /**
         * Allocates a <code>Date</code> object and initializes it so that
         * it represents the time at which it was allocated, measured to the
         * nearest millisecond.
         * @see     java.lang.System#currentTimeMillis()
        public Date() {
            this(System.currentTimeMillis());
        }

  • 1 month difference between OS time and System.currentTimeMillis()

    Hi all:)
    System.currentTimeMillis() give a time 1 month ago. If any one have idea what is wrong?Others programs give the right time.
    I tested on Windows XP Pro and Linux end the result is wrong on both OS.
    Thank you in advance.

    posman@linux:~/ivan> uname -a
    Linux linux 2.6.4-52-default #1 Wed Apr 7 02:08:30 UTC 2004 i686 i686 i386 GNU/Linux
    posman@linux:~/ivan> cat x.java
    public class x {
    public static void main(String args[]) {
    System.out.println(new java.util.Date());
    posman@linux:~/ivan> javac x.java
    posman@linux:~/ivan> date;java x
    Mon Feb 14 10:18:02 CET 2005
    Mon Feb 14 10:18:02 CET 2005

  • Does System.currentTimeMillis() cater for daylight saving

    My question is does System.currentTimeMillis by any means cater for the daylight savings time or in the other case when clocks are moved backwards it repeats it self???????
    Its pretty confusing isnt it?

    the whole problems with the currentTimeMillis is that it calculates the offset from the System clock - System TimeZone Offset
    if the System uses Manual DST or the auto DST is not checked (Windows)
    The the user of the system changes manually the clock and the calculation
    current millis will be wrong one hour
    for example I am in GMT + 2 + DST(1)
    GMT is 1200
    Local OS shows 1400, and I manually change it to 1500 (DST check box is not checked
    the Java will report GMT time 1300 (1500 - 2:00)
    whic is wrong.
    There is no indication wether this check box is checked or not
    If anyone knows how to find out if its checked please tell all

Maybe you are looking for

  • How do I change the default application to open files.

    I am rather new to Mac OS (using Leopard). I am rather frustrated, that I have not been able to find a way to change the default application that opens PDF files. I looked around the System Prefernces, couldn't find it, searched the Web, nothing. And

  • One website creates havoc with my iMac - what can be done?

    I am an administrator for our church website. When I go on it to work, after about 10 minutes either Safari or Firefox, whichever I'm using, freezes completely. I have to force quit and restart about every 10 minutes. In fact it isn't only that it fr

  • Problem in sending mail from database with attachment

    Hi All, I amd using forms10g,oracle10g I am facing a error while running a procedure to send mail from db procedure is: declare ErrorMessage VARCHAR2(4000); ErrorStatus NUMBER; -- enable SQL*PLUS output; --SET SERVEROUTPUT ON -- redirect java output

  • I WANT FEILD AND TABLE  NAME FOR VALUE OF UNRESTRICTED STOCK

    I WANT FEILD AND TABLE  NAME FOR VALUE(PRICE) OF UNRESTRICTED STOCK

  • I have an Icon I don't know what it is?

    There is an Icon that that is on the right hand side that looks like a pic of the phone with an envalope in front of it and it says 3 next to it, I know it is not voice mail or e-mail it is smaller then those icons . It is on the other side of the ti