timing an operation in java - 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.

Add a system.out.println at the end of your app to indicate how long it ran.

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).

Add the speed-tracer plugin to eclipse if it is a web application.It will help u find out the time for everything.

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();
}
}
});
}

Related

How to exit 2D game simulation (only) without exiting the Java code?

I (new to Java) am working on a decades old Java project built using Golden T Studios Game dev jdk. I have a game in the project which runs a 2D simulation. The code structure in a nutshell is as follows:
package game;
import java.io.*;
import java.lang.reflect.Field;
import javax.swing.JFrame;
import com.golden.gamedev.GameLoader;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import sometcpimports.*;
public class MainGAME extends JFrame implements Runnable {
public static void main(String[] args) { //call new MainGAME;
}
public MainGAME() {//initiate game parameters;
//start new THREAD;
}
#Override
public void run() { //initiate new game and environment;
game = new GameLoader();
gameenv = new GameEnvironment(params); //This class is in another file "public class GameEnvironment extends Game {}"
//I don't clearly undertsand what the following lines do, so I'm mentioning them as is;
game.setup(gameenv, dimensions);
this.setVisible(false);
gameenv.setVisible(false);
game.start();
game.setVisible(true);
//tbd (code reaches this step)
}
}
My goal is to run the above simulation multiple times (with different inputs each time) and extract information after each run in a new main class as follows.
public class gamedriver {
public static void main(String[] args) {
MainGAME.params = some params;
MainGAME.main(); // runs the simulation;
//tbd1 (code doesn't reach this step)
}
}
The issue is that, on running the simulation from a different file (new main class), I am unable to exit 2D simulator after one run. The code doesn't reach //tbd1 in the new main class which has some output print statements. Essentially I want to simply exit simulator and not the whole JVM. So far I've tried:
game.stop() & gameenv.finish() at //tbd which does nothing.
System.exit(0) at //tbd which exits game after simulation but also exits jvm and doesnt reach the other main class.
finish() at both //tbd and GameEnvironment class which behaves exactly like point 2.
Additionally, I am unable to run the above (MainGAME in gamedriver class) in a for loop. This throws Game.Exception error. I understand it has something to do with threads but I'm not sure how to run them.
Thank you for your time. Appreciate your help!
I found a method to solve the above problem. I'm posting my workaround as a reference for someone who encounters a similar issue. Please note that there might be other (better) solutions out there.
I disabled all (any) threads implementation in the MainGAME (by simply commenting it out).
I added System.out.println() in MainGAME to print all my outputs at the end of simulation.
My second script uses Runtime processes to execute MainGAME:
public class gamedriver {
public static void main(String[] args) {
try {
String separator = System.getProperty("file.separator");
String classpath = System.getProperty("java.class.path");
String path = System.getProperty("java.home") + separator + "bin" + separator + "java";
String[] command = new String[]{path, "-cp", classpath, gamedriver.GAME.class.getName(), "output.csv"};
Process process = Runtime.getRuntime().exec(command);
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
static class GAME {
public static void main(String args[]) {
PrintStream out = null;
try {
out = new PrintStream(args[1]);
} catch (FileNotFoundException p) {
p.printStackTrace();
}
System.setOut(out);// this catches all output from the game to a csv file (output.csv)
MainGAME temp = new MainGame(some params); // initiate the simulation
temp.run()
out.close();
System.exit(0); // force close the simulator
}
}
}
I parse output.csv to get the solution.
This might be a sloppy way to solve the issue, but it worked for me, especially because none of the other methods provided by GTGE worked.

Wait to preform function without freezing the process

I want to wait 300ms after 2 lines run to run the same 2 lines again, without freezing the thread.
wait(300); and Thread.sleep(300);, along with some loop I found on SO (below) either freeze the thread, exit cleanly(?) or lag the thread by running the function a million times.
I want to wait 300 milliseconds and then run
mc.player.rotationPitch = 90;
mc.playerController.processRightClick(mc.player, mc.world, hand);
without freezing the thread, as sometimes it doesn't time properly if the thread is frozen, and it's annoying for the user if it's going to freeze every time.
I've tried wait, Thread.sleep, TimeUnit.MILLISECONDS.sleep and
long lastNanoTime = System.nanoTime();
long nowTime = System.nanoTime();
while(nowTime/1000000 - lastNanoTime /1000000 < 300 )
{
nowTime = System.nanoTime();
System.out.println("KAMI: Tried to pick up bucket");
}
I've already shown the relevant examples above.
Full code is here
Expected: thread works normally, and my 2 lines, (rotation pitch and right click) run 300 milliseconds after the previous rotation pitch and right click
Actual results: commented in code. Depending on the method used thread either lags, exits or crashes
You will need another thread to do this "without freezing" the current thread. This can be done quite easily, something like:
import java.lang.Thread;
public class Main {
public static abstract class After extends Thread {
private int sleep = 0;
public After(int sleep) {
this.sleep = sleep;
}
public void run() {
try {
Thread.sleep(this.sleep);
} catch(InterruptedException e) {
//do something with e
}
this.after();
}
public abstract void after();
}
public static void main(String[] args) {
After after = new After(300) {
public void after() {
//mc.player.rotationPitch = 90;
//mc.playerController.processRightClick(mc.player, mc.world, hand);
System.out.println("testing");
}
};
after.start(); //this will execute the code in 300 ms
//do what ever you want to do during the 300ms
after.join(); //join all threads at the end of your code
System.out.println("done");
}
}
Use After when you want to create a delay. Hope this helps!

Java Multithreading: How can i start external Java Programs, which are executing threads?

currently, i'm trying to write a programm, which should execute a seperate Java-program multiple times, but with different parameters. This executed Java-program calls a Thread-Class. Within this class, a connection to a (Game)Server is established. Once connected, the Threads sends a command to turn the connected player around every 10 milliseconds. I have 2 "solutions" for this:
The easy (working) one:
public class GeneralAgentTest {
public static void main(String [] args){
Thread thread = new Thread(new HexagonRunner("127.0.0.1",6000,"UnitedTestors",-30,-15));
thread.start();
}
}
This is working correctly, but not actually my goal. I need to start several of this Threads (new Thread(new HexagonRunner("127.0.0.1",6000,"UnitedTestors",-30,-15)); ) and each of this threads must be handled by a seperate process.
To do this, i wrote some code with an ProcessBuilder. This is within one class.
Second not correctly working one:
public void execute(Class class1, int a, String str, String team, String x,
String y) {
ProcessBuilder builder;
String javaHome = System.getProperty("java.home");
String javaBin = javaHome + File.separator + "bin" + File.separator
+ "java";
String classpath = System.getProperty("java.class.path");
String className = class1.getCanonicalName();
builder = new ProcessBuilder(javaBin, "-cp", classpath,
className, ip, port, team, str, x, y);
try {
process[a] = builder.start();
} catch (Exception e) {
e.printStackTrace();
System.out.println("failed");
}
public void loadPlayers() {
process = new Process[4];
for (int i = 0; i < 4; i++) {
try {
execute(processes.StartProcesses.class, i,
playerCombo[i].getSelectedItem().toString(),
playerTeam[i].getText(), playerStartX[i].getText(),
playerStartY[i].getText());
} catch (Exception e) {
System.out.println("Failed to create processes for players");
e.printStackTrace();
}
}
}
These are the functions i wrote, to execute the class(es) who is/are starting the thread(s).
Following class is executed:
public class StartProcesses{
public static void main(String[] args) {
Thread t = null;
t = new Thread(new HexagonRunner("127.0.0.1",6000,"UnitedTestors",-30,-15));
t.start();
JOptionPane.showMessageDialog(null, "should've started");
}
}
In my second try, the parameters which are given to the StartProcesses Class are containing some information like IP-Adresses, Portnumbers, Playerpositons and stuff like this. Anyway i was trying to execute the class with "hard" information, just to be sure it is working like in my first codepart.
The connections to the server are correctly established in both attempts, but in the first one the thread keeps working. In my second try it seems like the thread is dead after the connection is established. The process is still alive, since the connection to the server is still there.
This is a bit of code, but what i want to tell, is that the Thread is working correctly when executed manually, but it is not working correctly if i try to start the class automatically with the use of ProcessBuilders.
I really really hope you guys could understand what i am trying to say. Hopefully someone has a working solution for me.
Cheers.
EDIT: Add Code for HexagonRunner:
public class HexagonRunner extends GeneralAgent {
// Bunch of Methods
// Important Method:
#Override
protected void simulationCycle() {
turnAgent(40);
}
}
The simulationCycle() method, is the method that is going to be go through over and over again.
Since the class HexagonRunner is inherited from the class GeneralAgent, i'm going to post the relevant stuff of this class here as well:
public class GeneralAgent implements Runnable, UdpListener{
// Attributes, getters, setters, methods..
#Override
public final void run() {
// giving the worker threads the signal to start
mServerConnection.start();
mParser.start();
// waiting for the first information to be parsed, so that the
// simulation loop can run
try{
System.out.println("GeneralAgent-Run: waiting for latch");
mLogger.info("Run method: waiting for CountDownLatch");
mFirstDone.await();
}
catch(InterruptedException e){
System.out.println("GeneralAgent-Run: InterruptedException");
mLogger.info("Run method error: " + e.getMessage());
}
mLogger.info("Run method: CountDownLatch now 0, continue");
// setting the initial position
moveToPostion(mXStartCoord, mYStartCoord);
// the simulation loop
while (true){
simulationCycle();
// Shutdown if the game is over
if (mGameworld.getTime() >= 6000){ // later 6000+
System.out.println("Yeah, 50 runs completed -> Shutdown");
mLogger.info("General Agent - Time > 50, programm should terminate");
shutdown();
break;
}
// waiting for the threads to signal that they are
// ready (e.g. have new server information)
// for another round of the simulation loop
mPhaser.arriveAndAwaitAdvance();
}
}
I hope things get clearer now. I still have no idea where my code fails.
You could build somethin a lot simpler by using Executors. It' part of the comcurrent package introduced in Java 1.5. It basically works as follows:
// create a pool with 10 threads
ExecutorService executorService = Executors.newFixedThreadPool(10);
//loop as long as you need to detach your threads
for (int i = 0; i < 4; i++) {
// this actually contains the thread bit, will be executed in parallel
executorService.execute(new Runnable() {
public void run() {
// this is where your code is
new HexagonRunner("127.0.0.1",6000,"UnitedTestors",-30,-15)
}
});
}
// clean up when you're done to prevent leaks
executorService.shutdown();
That's it, much simple and you don't need to spawn different JVMs through ProcessBuilder, which is a lot slower.

Java clock error

I was making a clock, which displays time in Java, I will show the code below:
public class MyApp extends javax.swing.JFrame {
int timeRun = 0;
/**
* Creates new form MyApp
*/
public MyApp() {
initComponents();
System.out.println("We'll start here!");
new Thread ()
{
public void Run(){
while(timeRun == 0)
{
Calendar cal = new GregorianCalendar();
int hour = cal.get(Calendar.HOUR);
int min = cal.get(Calendar.MINUTE);
int sec = cal.get(Calendar.SECOND);
int AM_PM = cal.get(Calendar.AM_PM);
String time = hour + ":" + min + ":" + sec;
System.out.print(time);
System.out.print("We'll end here!");
}
}
}.start();
}
I have a JLabel, and the other components needed for this JFrame to work.
I also have main set up, although you can't see it in the example above
My issue is, that I can't get a value from time, nor can I print "We'll end here" inside the Run, I'm new to Java, so any help would be much appreciated.
My console prints this:
run:
We'll start here!
BUILD SUCCESSFUL (total time: 6 seconds)
You've created a thread, but you haven't overridden the run method - instead you've created a Run method. Java is case-sensitive. Change this:
public void Run() {
...
}
to this:
#Override
public void run() {
...
}
Using #Override asks the compiler to validate that you really are overriding something - if you'd used that before, you'd have received a compile-time error.
Additionally, I'd recommend implementing Runnable and passing that to the Thread constructor instead of overriding run in Thread itself:
Runnable runnable = new Runnable() {
#Override
public void run() {
...
}
};
new Thread(runnable).start();
Again, if you'd implemented the interface instead of creating an anonymous subclass of Thread, the compiler would have picked up the problem.
EDIT: As noted in comments, your loop is never-ending, too... but you'll see that when it actually gets as far as running.
The thread's method you must override is run. Because that's the one you are inheriting and which is intented to actually run what thread must do.
So:
It's all about inheritance.
Add #Override annotations in such codes. (IDE should have suggested it).
Remember Java is case sensitive.
Stick to Camel notation. In Java, all is supposed to be coded according to it.
4.1 Classes and Interfaces are supposed to start with capital letters.
4.2 Attributes and methods are supposed to start with small letters.
You should have done:
#Override
public void run() {
//Your code here
}

Java threads problem

I have a problem with java threads:
public class MyClass{
public void Core(){
runTools(); //here I would like to call runTools() method
}
public void runTools(){
final String run_tool ="cmd.exe /C sources.exe";
Runnable doRun = new Runnable() {
public void run() {
try {
Process tool_proc = Runtime.getRuntime().exec(run_tool);
}
catch (IOException e) {
e.printStackTrace();
}
}
};
Thread th = new Thread(doRun);
th.start();
}
}
If I do this, then I don't know why, but the thread doesn't work. Please give me some ideas to create a thread. I have already been seen lots of examples, but I should some code such as my example here. Thanks!
At first, if you just want to execute an external command and do not bother about its output*, then using a dedicated thread is unnecessary, since the process itself will already run in parallel to your application, so the exec() call will not really hang your programm.
Nevertheless your code looks correct to me. You should check the working directory of your application (maybe cmd.exe cannot find your sources.exe) and evaluate the output the process you start gives you, by directing the streams of tool_proc.getErrorStream() and tool_proc.getInputStream() to System.out or logging them.
EDIT:
* The Java documentation states you always should read the InputStreams of your processes as failing to do so might result in filling up a system buffer, which will eventually hang the process.
problem 1 You create object for Runnable Interface,that is never possible.
Runnable *obj=new Runnable(); // this is not correct
problem 2 You write definition for Run() method with in the another method runTools()
we can create object for a class that implements The Runnable interface.
Due to these your code is not working.
Try the fallowing way
public class MyClassName1 implements Runnable
{
public void start()
{
//here you can call your method:runTools()
runTool();
}
}
public void runTools()
{
final String run_tool ="cmd.exe /C sources.exe";
try
{
Process tool_proc = Runtime.getRuntime().exec(run_tool);
}
catch (IOException e)
{
e.printStackTrace();
}
}
here is my main class of the programe
public class MyClassName2
{
public static void main(String[] ars)
{
Runnable *obj1=new MyClassName1();
Thread t=new Thread(obj);
t.start()
}
I hope this helps to you

Categories