简体   繁体   中英

timing an operation in java

I want to run my program in eclipse but I want to see how long it takes to run the program. In other words I want to time my program. I know that in UNIX I can time any operation by placing the word “time” before the command on the command line. But I dont know how I might be able to time my operation in Eclipse. Just to make everything a bit more clear, I want to avoid writing new methods. Is there a way that I could add sth to my configuration path? Does anyone have an idea of how I can do so?

If you don't mind adding two lines of code, you can do this purely in Java:

public class Foo {
    public static void main(String[] args) {
        long ms = System.currentTimeMillis();

        // do whatever

        System.out.println(System.currentTimeMillis() - ms);
    }
}

You could also use nanoTime if you need it.

在应用程序的末尾添加system.out.println以指示其运行了多长时间。

Put this class somewhere in your code:

package your.package.name.common;

import org.apache.log4j.Logger;

import java.util.concurrent.TimeUnit;

public class CProfile {
    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(CProfile.class);

    public static final int SECONDS_TO_ALERT = 2;

    public static void slownessAlert(long startTime, String name) {
        long seconds = TimeUnit.SECONDS.convert(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);
        if (seconds>SECONDS_TO_ALERT){
            logger.warn("slow method detected: "+name+" "+seconds+"s");
        }
    }

}

Then use this snippet in your code in following way:

public void something() {
    long startTime = System.nanoTime();

    //SOME HEAVY COMPUTATIONS

    CProfile.slownessAlert(startTime, "something");
}

It will inform you about slowness when it happens (SECONDS_TO_ALERT>2s).

如果它是一个Web应用程序,则将speed-tracer插件添加到eclipse中,它将帮助您找出所有时间。

A simple way to do this and guarantee you will get results is to add the following to the top of your main class. This code will save the app start time and then add JVM shutdown hook that will fire and print the duration when the JVM shutsdown.

final static long startTime = System.currentTimeMillis();
static {
Runtime.getRuntime().addShutdownHook(new Thread() {
    public void run() {
        try {
            System.out.println("My program ran for "+( System.currentTimeMillis()-startTime )+" seconds.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM