May I know How to insert a stop watch for this piece of code from Poll() method...I have to make start count such that before the database starts and amount of time it took for polling.
public void poll() throws Exception {
st = conn.createStatement();
for (int i=0; i<10; i++)
{
Timestamp start;
rs = st.executeQuery( "select * from msg_new_to_bde" );
Timestamp end;
//speed = end - start;
Collection<KpiMessage> pojoCol = new ArrayList<KpiMessage>();
while (rs.next()) {
KpiMessage filedClass = convertRecordsetToPojo(rs);
pojoCol.add(filedClass);
}
for (KpiMessage pojoClass : pojoCol) {
System.out.println("=== Iteratioin Nr. " + i + "====");
System.out.print(pojoClass.getSequence());
System.out.print(pojoClass.getTableName());
System.out.print(pojoClass.getEntryTime());
System.out.print(pojoClass.getProcessingTime());
System.out.println(pojoClass.getStatus());
// System.out.println(pojoClass.getprocessDuration());
}
System.out.print(pojoCol.size());
}
}
You have to use currentTimeMillis() function:
Before launch polling:
long start = System.currentTimeMillis();
After Polling execution:
long stop= System.currentTimeMillis();
Execution time is stop - start in milliseconds.
I believe System.currentTimeMillis is what you looking for.
long startTime = System.currentTimeMillis();
//
long endTime = System.currentTimeMillis();
System.out.println((endTime - startTime) + "ms");
java.util.Date date = new java.util.Date();
Timestamp start = new Timestamp(date.getTime());
//process
java.util.Date date1 = new java.util.Date();
Timestamp end = new Timestamp(date1.getTime());
long start = System.currentTimeMillis();
rs = st.executeQuery( "select * from msg_new_to_bde" );
long stop= System.currentTimeMillis();
System.out.println("execution time: " +stop-start + " ms");
long start = System.nanoTime();
timeThisMethod();
long end = System.nanoTime();
long howLongDidItTake = end - start;
This method is more precise then System.currentTimeMillis()
Citation from java API :
Returns the current value of the most precise available system timer,
in nanoseconds.
Related
I want to store time slot in the arraylist. i have start time and end time. based on start time it should create time slot.
For example if start time is 09:00AM and end time is 21:00PM then it should add into arraylist like below
09:00AM
10:00AM
11:00AM
12:00PM
13:00PM
14:00PM
..... so on
21:00PM
so one user books 13:00PM to 15:00PM slots so it should not be available to another user and other slot should be available. how to compare already booking time with new array list.
Code
private void getStartHourArray() {
times = new ArrayList<TimeSlot>();
Calendar calender = Calendar.getInstance();
calender.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
int ti = calender.get(Calendar.HOUR_OF_DAY);
int minutes = calender.get(Calendar.MINUTE);
System.out.println(minutes);
String[] quarterHours = {
"00",
"30",
};
boolean isflag = false;
times = new ArrayList<>();
for (int i = 9; i < 22; i++) {
if (ti > 8) {
for (int j = 0; j < 2; j++) {
if ((i == ti && minutes < Integer.parseInt(quarterHours[j])) || (i != ti) || isflag == true) {
isflag = true;
String time = i + ":" + quarterHours[j];
if (i < 10) {
time = "0" + time;
}
String hourFormat = i + ":" + quarterHours[j];
if (i < 12) {
hourFormat = time + " AM";
} else
hourFormat = time + " PM";
TimeSlot t = new TimeSlot();
t.time = hourFormat;
t.isAvailable = "Available";
times.add(t);
}
}
}
}
if (times != null) {
load.setVisibility(View.GONE);
}
}
Time Slot model class
public class TimeSlot {
public String time;
public String isAvailable;
}
Try something like this :
String firstDate = "26/02/2019";
String firstTime = "00:00 AM";
String secondDate = "26/02/2019";
String secondTime = "12:00 PM";
String format = "dd/MM/yyyy hh:mm a";
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date dateObj1 = sdf.parse(firstDate + " " + firstTime);
Date dateObj2 = sdf.parse(secondDate + " " + secondTime);
System.out.println("Date Start: "+dateObj1);
System.out.println("Date End: "+dateObj2);
long dif = dateObj1.getTime();
while (dif < dateObj2.getTime()) {
Date slot = new Date(dif);
System.out.println("Hour Slot --->" + slot);
dif += 3600000;
}
This will give you a time slot for each hour, add this in ArrayList and when any user select time then remove that from ArrayList and update to the server so when next
user tries to get data it won't get the first selected user time slot.
try this:
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;
public class PlayGround {
private Map<LocalTime, Boolean> slots = new HashMap();
public static void main(String[] args) {
PlayGround client = new PlayGround();
client.initializeSlots();
client.allocateSlots("10:00", "13:00");
//this shouldn't be available
client.allocateSlots("11:00", "12:00");
//not sure if u want this to be available. since it is start when the 1st just finished.
client.allocateSlots("13:00", "15:00");
client.allocateSlots("16:00", "18:00");
}
private void initializeSlots() {
LocalTime time = LocalTime.of(9, 0);
slots.put(time, true);
for (int i = 1; i < 24; i++) {
slots.put(time.plusHours(i), true);
}
}
private void allocateSlots(String strTime, String edTime) {
LocalTime startTime = LocalTime.parse(strTime);
LocalTime endTime = LocalTime.parse(edTime);
while (startTime.isBefore(endTime)) {
//check if the time slots between start and end time are available
if (!slots.get(startTime) || !slots.get(endTime)) {
System.out.println("slots not available" + " start time: " + strTime + " end time: " + edTime);
return;
}
startTime = startTime.plusHours(1);
endTime = endTime.minusHours(1);
}
System.out.println("slots are available" + " start time: " + strTime + " end time: " + edTime);
//then here u can mark all slots between to unavailable.
startTime = LocalTime.parse(strTime);
endTime = LocalTime.parse(edTime);
while (startTime.isBefore(endTime)) {
slots.put(startTime, false);
slots.put(endTime, false);
startTime = startTime.plusHours(1);
endTime = endTime.minusHours(1);
}
}
}
I am working with websockets, i want the process of sending/recieving data be as fast as possible. I have come across BSON and MsgPack libraries for binary serialization. However, using simple tests:
#Message
class MessageTemplate implements Serializable {
public String msg;
}
public class test {
static void start(){
MessageTemplate x = new MessageTemplate();
for (int i = 0; i < 1000; ++i)
x.msg += UUID.randomUUID().toString();
System.out.println("===============================================================");
{
long startTime = System.nanoTime();
byte[] bytes = SerializationUtils.serialize(x);
MessageTemplate x1 = (MessageTemplate) SerializationUtils.deserialize(bytes);
long endTime = System.nanoTime();
long duration = (endTime - startTime);
System.out.println("TIME1:" + String.valueOf(duration) + ", SIZE: " + bytes.length);
}
System.out.println("===============================================================");
MessagePack msgpack = new MessagePack();
{
long startTime = System.nanoTime();
try {
byte[] b = msgpack.write(x);
MessageTemplate dst = msgpack.read(b, MessageTemplate.class);
long endTime = System.nanoTime();
long duration = (endTime - startTime);
System.out.println("TIME1:" + String.valueOf(duration) + ", SIZE: " + b.length);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Output:
starting===============================================================
TIME1:2560388, SIZE: 36171
===============================================================
TIME1:93729732, SIZE: 36013
It seems that serialization is way faster than MsgPack. However searching i have found not any mentioning of java serialization as "serializating library/format".
What are the drawbacks of using it? Why is it or isnt used? The only drawback i see is that mobile app will have ios/android client, so there wont be java on both sides in every case.
Thanks for help and answers.
I want to add records I database table with some interval of time using jdbc.
For ex., I want to add 100000 records in 10 sec interval so it'll insert 10000/sec.
My code of MySQL as below :
String url1 = "jdbc:mysql://localhost:3306/xyz";
String user = "root";
String password = "root";
conn1 = DriverManager.getConnection(url1, user, password);
if (conn1 != null) {
System.out.println("Connected to the database xyz");
for(int i=0;i<=n;i++){ // where n is no. of record that I want to insert
// Here is my insert logic
}
}
#yogesh-jalodara In my comments I meant something like that
final long loopDuration = 1;//second
final long totalSize = 100000;
final long timeInterval = 10;
final AtomicLong batchNumber = new AtomicLong((long)Math.ceil((double) timeInterval / loopDuration));
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
//insert logic
if (batchNumber.decrementAndGet() == 0) {
timer.cancel();
timer.purge();
}
}
}, 0, loopDuration * 1000);
Using batch queries, You effectively reduce database round-trip, You save a lot of time spent on network latency, which results in better performance of Java application.
public class MySQLJdbcExample {
public static void main(String args[]) throws SQLException {
String url="jdbc:mysql://localhost:3306/test";
Connection conn = DriverManager.getConnection(url, "root", "root");
String query = "insert into employee values (?,?,NULL)";
PreparedStatement pStatement = conn.prepareStatement(query);
int batchSize = 100;
long startTime = System.currentTimeMillis();
for (int count = 0; count < 1000; count++) {
pStatement.setString(1, Integer.toString(count));
pStatement.setString(2, "Employee" + count);
pStatement.addBatch();
if (count % batchSize == 0) {
pStatement.executeBatch();
}
}
pStatement.executeBatch() ; //for remaining batch queries if total record is odd no.
// conn.commit();
pStatement.close();
conn.close();
long endTime = System.currentTimeMillis();
long elapsedTime = (endTime - startTime)/1000; //in seconds
System.out.println("Total time required to execute 1000 queries using PreparedStatement with JDBC batch insert is :" + elapsedTime);
}
}
Read more: http://javarevisited.blogspot.com/2013/01/jdbc-batch-insert-and-update-example-java-prepared-statement.html#ixzz47Bgqyx64
My scenario is to create time in a particular pattern
For ex : startTime and duration will be entered by the user.
let startTime be 9:00:00 and duration is 60s. Now my output should be like add up 60sec to my starttime and set that as end time. Then add 10mins to startTime and again add 60s to it and set it as endtime. this will be iterated within a loop.
I have done somepart of that work and i got partial output,
THe output is got is like
startTime : 9:00:00
EndTime : 9:01:00
startTime : 9:00:00
EndTime : 9:01:00
startTime : 9:00:00
EndTime : 9:01:00
But the expected output is like
startTime : 9:00:00
EndTime : 9:01:00
startTime : 9:11:00 // HERE ADDING 10mins to startTime and assigning it as startTime again
EndTime : 9:12:00 // Adding 60sec duration to the updated startTime
startTime : 9:20:00
EndTime : 9:21:00
My code :
public static void main(String[] args) throws ParseException {
String myTime = "090000";
for(int i=0;i<3;i++){
SimpleDateFormat df = new SimpleDateFormat("HHmmss");
Date d = df.parse(myTime);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.add(Calendar.SECOND, 60);
String newTime = df.format(cal.getTime());
System.out.println("Start time : "+myTime);
System.out.println("end Time :"+newTime);
}
You forgot to add the 10 minutes at the end of the loop. (Also, you don't need to create the SimpleDateFormat in every loop).
public static void main(String[] args) throws ParseException {
SimpleDateFormat df = new SimpleDateFormat("HHmmss");
String myTime = "090000";
for(int i=0;i<3;i++){
Date d = df.parse(myTime);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.add(Calendar.SECOND, 60);
String newTime = df.format(cal.getTime());
System.out.println("Start time : "+myTime);
System.out.println("end Time :"+newTime);
// now add 10 minutes to the start time
cal.setTime(d);
cal.add(Calendar.MINUTE, 10);
myTime = df.format(cal.getTime());
}
}
Thank you in advance for your help. I am developing a java based tool that is preforming some database work. I have a very simple problem. For some reason the time reported to complete the task is incorrect.
public static void makeDatabaseThreaded() throws IOException, InterruptedException {
final long startTime = System.nanoTime();
ArrayList<String> tablesMade = new ArrayList<>();
File rootDirectory = root;
String[] files = rootDirectory.list();
double percentDone = 0;
double numOfTablesMade = 0;
double numberOfTables = 62.0;
DatabaseBuilderThread lastThread = null;
for (int i = 0; i <= files.length - 1; i++) {
if (!files[i].contains(".csv")) {
continue;
}
File file = new File(rootDirectory + File.separator + files[i]);
String tableName = getTableNameFromFile(file);
if (!tablesMade.contains(tableName)) {
tablesMade.add(tableName);
DatabaseBuilderThread thread = new DatabaseBuilderThread(i, file);
lastThread = thread;
thread.start();
threadsRunning++;
numOfTablesMade++;
percentDone = (int) (100.0 * (numOfTablesMade) / (numberOfTables));
while (threadsRunning > 10) {
Thread.sleep(1000);
}
System.out.println(percentDone + "% done. Making Table For File: " + file.getName());
}
}
//Make Sure all threads are done
lastThread.join();
final long endTime = System.nanoTime();
final long duration = endTime - startTime;
Time time = new Time(duration);
System.out.println("Done Making The Database. It took " + time.toString());
}
The program reports that it worked about twice as long at it truly did for the cases that I ran.
Thanks
System.nanoTime() returns time values in nanoseconds. Time() takes a value in milliseconds as a parameter. This would throw your time value off by a factor of 10^-6.
Time takes milliseconds as a constructor parameter, where as nanoTime() gives you nanoseconds precision, could that be the problem?
discussion here: System.currentTimeMillis vs System.nanoTime