In the code below, I don't understand why the diference in elapsed time calculated with System.currentTimeMillis() is different tm.getCurrentThreadUserTime()

The elapsed time in millisecond is always a value like 23 or 14 while time calculated with tm.getCurrentThreadUserTime() is always 0 . I know one is milli and the other is nanosecond. Even then why is it 0?

public void animationLoop() {
        long startTime = System.currentTimeMillis();
        long currTime = startTime;

        int count = 0;
        ThreadMXBean tm = ManagementFactory.getThreadMXBean();
        long cpuTime = 0;
        long cpuTimeElapsed = 0;
        while (currTime - startTime < DEMO_TIME) {
        	long elapsedTime = System.currentTimeMillis() - currTime;
            cpuTimeElapsed = tm.getCurrentThreadUserTime() - cpuTime;
            //currTime += elapsedTime;
            currTime = System.currentTimeMillis();
	    	cpuTime = tm.getCurrentThreadUserTime();
	    	System.out.println("CPU Time: "+ cpuTimeElapsed +" Elapsed Time: "+elapsedTime);
            // update animation

            // draw to screen
            Graphics g = screen.getFullScreenWindow().getGraphics();
            System.out.println("Iteration: "+ count+ " Elapsed time: " + elapsedTime);


This code is taken from Brackeen's Game programming in Java.

Is your OS multi tasking? Can the OS use time while your code is executing?


What class is the tm object?

Yes its a multitasking OS.
tm is of type ThreadMXBean.

I wouldn't have been surprised if milli gave zero and nano gave nonzero value. Unfortunately its the other way round.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.18 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.