开发者

How to call the Main function of Java file several times?

Please i need to call the main function of a java file sever开发者_运维知识库al times like (100) times and measure the time it takes for it to complete. The objective is comparing the time with some other files. [literally speaking, I'm Implementing Algorithms].

I know that calculating the time can be achieved by:

long startTime = System.currentTimeMillis();
GetExecutionTimes ext=new GetExecutionTimes();

ext.callMethod();
long endTime = System.currentTimeMillis();

System.out.println("Total elapsed time in execution of method callMethod() is :"
+ (endTime-startTime));

*Where ("callMethod") is the name of my method.

However, if i have a complete java file and i want to call its main function from another class (or file) while calculating its execution time, what's the way to do that?

In Summary:

Task 1: Calling the main function of a java file several times from another class.

Task 2: Calculating the time it takes to execute (Task 1).

Please any suggestions or ideas for accomplishing tasks 1 and 2 are greatly appreciated.

Thanks in advance for your help,


If you want to call it several times, I would use a loop. You can call a main(String[]) method several times, however you may be better off calling the underlying algo.


Beware of doing such benchmarks without a good understanding of the JVM, JIT, garbage collection, and how the differing non-program threads can confound your benchmarking.

You can collect good benchmarks, but doing so eventually becomes a statistical challenge, as the measurements are rather noisy (due to the JVM scheduling garbage collection every now and then, the JVM pausing to compile your code to native instructions, and the native instructions generally running much faster than non-native).

That said, you can call the static main method just like any other static method. Note that you probably need to store off the args array if you really want to have the "same" call.


Can you try with creating a JUnit test case and in the runner call your test's method (which internally will call the actual object's main). That way you might get the execution times via JUnit.


main() is just a public, static method in a class, so you can always just call it like

for (int i = 0; i < 100; i++) {
    MyClassWithMain.main(null);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜