How can I get seconds and milliseconds together from time? - java

I am trying to get page load time in automation testing project.
pageLoad3.start();
WebDriverWait wait3 = new WebDriverWait(driver, 30);
wait3.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(hotelNameDetailsXpath)));
pageLoad3.stop();
long pageLoadTime_ms5 = pageLoad3.getTime();
long pageLoadTime_Seconds5 = pageLoadTime_ms5 / 1000;
//System.out.println("Time taken to get load Total price element ::");
System.out.println("pageLoadTime_ms5 ::"+pageLoadTime_ms5);
System.out.println("Time taken to load DB Response :: " + pageLoadTime_Seconds5 + " seconds");
Output:
pageLoadTime_ms5 ::11479
Time taken to load DB Response :: 11 seconds
I am getting 11 seconds but not able to get for 479, how can I get it in below format?
Actual Requirement: I want time to get in below format like
11 seconds 47 milliseconds i.e. (00:11:47)

To get the output as 11 seconds 47 milliseconds you can use the following solution:
Code Block:
public class division_by_1000 {
public static void main(String[] args) {
//long pageLoadTime_ms5 = pageLoad3.getTime();
// assuming pageLoadTime_ms5 = 11479
String pageLoadTime_ms5 = "11479";
System.out.println("pageLoadTime_ms5 ::"+pageLoadTime_ms5);
System.out.println("Time taken to load DB Response :: " + (Integer.parseInt(pageLoadTime_ms5)/1000) + " seconds " + (Integer.parseInt(pageLoadTime_ms5)%1000) + " millisseconds ");
}
}
Console Output:
pageLoadTime_ms5 ::11479
Time taken to load DB Response :: 11 seconds 479 millisseconds

Related

Difference between todays Date and older Date not calculating correctly

I know this has been asked before but I can't find my exact problem.
When the user clicks a button to add a marker to a map, I am storing a true boolean tagUserLocation (to tell my Map Activity onCreate that there is a latitude and longitude stored for the users location, which needs to be added to the database before populating the map). The user then sees an activity with radio buttons to select the type of marker.
When they select the marker type and click the positive button in an Alert dialog, I am storing the number of markers the user had added and the date for the most recent one addedTagDate to my Shared Preferences. This is so I can prevent the user adding another marker for a while.
When my Map activity starts in the onCreate, it detects the tagUserLocation is true, and triggers a method to store the new marker details to the DB before creating the Map.
This is the onClick method for the Alert dialog that sets the addedTagCount and addedTagDate in millis. IT then directs the user back to the Map activity which detects there is a new marker and saves it to the DB before recreating the map.
builder.setPositiveButton(yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
int i = sharedPreferences.getInt("addedTagCount", 0);
Log.i(TAG, "Testing_" + "posButton 1 " + " " + i);
if(i < 1){
Date todaysDate = new Date();
long millis = todaysDate.getTime();
i++;
sharedPreferences.edit().putInt("addedTagCount", i).commit();
sharedPreferences.edit().putLong("addedTagDate", millis).commit();
Log.i(TAG, "Testing_" + "posButton 2 " + " " + i);
}
Intent intentMapsActivity = new Intent(context, Activity_MapsActivity.class);
context.startActivity(intentMapsActivity);
passedActivity.finish();
dialog.dismiss();
}
});
When the user tries to add another marker, I am checking the stored addedTagDate against todaysDate to see if a certain amount of time has expired before allowing him to add another marker.
public boolean checkTimerForNewTag(Activity passedActivity) {
SharedPreferences sharedPreferences = passedActivity.getSharedPreferences("com.name.myApp", Context.MODE_PRIVATE);
//Check if timer to allow another tag has expired
Date todaysDate = new Date();
Date taggedDate = new Date(sharedPreferences.getLong("addedTagDate", 0));
long taggedDateAsLong = taggedDate.getTime();
Log.i(TAG, "checkTimerForNewTag_" + "taggedDateAsLong: " + taggedDate.getTime());
if (taggedDateAsLong != 0) {
long diffInMillis = todaysDate.getTime() - taggedDate.getTime();
long sec = diffInMillis / 1000;
long min = sec / 60;
long hours = min / 60;
Log.i(TAG, "checkTimerForNewTag_" + "Date Adjust: " + taggedDate.getTime() + " - " + todaysDate.getTime() + " = diffInMills: " + diffInMillis + " and sec: " + sec + " and min: " + min + " and hours: " + hours);
if (sec >= 20) {
Log.i(TAG, "checkTimerForNewTag_" + " hours > 1");
sharedPreferences.edit().putInt("addedTagCount", 0).commit();
sharedPreferences.edit().remove("addedTagDate").commit();
return true;
}
}
return false;
}
The first marker is added, and the addedTagDate stored. But when the user clicks the button a 2nd time the checkTimerForNewTag() gives a time difference which is incorrect. It is too little. Example repro steps:
Expected Outcome:
User clicks button
User redirected to Map activity
1st Marker added.
User waits 30 seconds and clicks
button again
Time difference is >=20 seconds
2nd Marker Added.
Actual Outcome:
User clicks button
User redirected to Map activity
1st Marker added.
User waits 30 seconds and clicks button again
Time difference is only 81 (Or 70, 44, 126 etc.) milliseconds.
User clicks button again after a few seconds
Time difference is correct and if >= 20 sec a 2nd Marker is added.
Log:
1st click works fine, a marker is added and the addedTagCount is stored to SP's.
2020-03-08 17:06:12.327 17912-17912/com.name.myApp I/UserTagging_: checkTimerForNewTag_taggedDateAsLong: 1583687115677
2020-03-08 17:06:12.327 17912-17912/com.name.myApp I/UserTagging_: checkTimerForNewTag_Date Adjust: 1583687115677 - 1583687172327 = diffInMills: 56650 and sec: 56 and min: 0 and hours: 0
2nd click did not work, I waited 30 seconds but the diff is only 81 millis.
2020-03-08 17:06:16.134 17912-17912/com.name.myApp I/UserTagging_: checkTimerForNewTag_taggedDateAsLong: 1583687176053
2020-03-08 17:06:16.134 17912-17912/com.name.myApp I/UserTagging_: checkTimerForNewTag_Date Adjust: 1583687176053 - 1583687176134 = diffInMills: 81 and sec: 0 and min: 0 and hours: 0
3rd click works, I waited 2 seconds, 7 sec and 12 sec - Everything is working again.
2020-03-08 17:06:18.100 17912-17912/com.name.myApp I/UserTagging_: checkTimerForNewTag_taggedDateAsLong: 1583687176053
2020-03-08 17:06:18.101 17912-17912/com.name.myApp I/UserTagging_: checkTimerForNewTag_Date Adjust: 1583687176053 - 1583687178100 = diffInMills: 2047 and sec: 2 and min: 0 and hours: 0
2020-03-08 17:06:23.072 17912-17912/com.name.myApp I/UserTagging_: checkTimerForNewTag_taggedDateAsLong: 1583687176053
2020-03-08 17:06:23.072 17912-17912/com.name.myApp I/UserTagging_: checkTimerForNewTag_Date Adjust: 1583687176053 - 1583687183072 = diffInMills: 7019 and sec: 7 and min: 0 and hours: 0
2020-03-08 17:06:28.248 17912-17912/com.name.myApp I/UserTagging_: checkTimerForNewTag_taggedDateAsLong: 1583687176053
2020-03-08 17:06:28.249 17912-17912/com.name.myApp I/UserTagging_: checkTimerForNewTag_Date Adjust: 1583687176053 - 1583687188248 = diffInMills: 12195 and sec: 12 and min: 0 and hours: 0
I have scoured my app to make sure I'm not doing anything untoward with the shared pref value. I'm convinced it must be a rounding problem or something similar with the Date function. Any ideas are much appreciated?
In checkTimerForNewTag you have:
sharedPreferences.edit().putInt("addedTagCount", 0).commit();
You check this in your first method:
int i = sharedPreferences.getInt("addedTagCount", 0);
if(i < 1){
Date todaysDate = new Date();
long millis = todaysDate.getTime();
i++;
sharedPreferences.edit().putInt("addedTagCount", i).commit();
sharedPreferences.edit().putLong("addedTagDate", millis).commit();
Log.i(TAG, "Testing_" + "posButton 2 " + " " + i);
}
Wouldn't i always be < 1 given you set it to 0 in checkTimerForNewTag?
FINALLY GOT IT!!!!!
I need to have an 'old date value' and a 'new date value', in addition to the immediate date value that I compare against. Whenever the time is updated I move the new one into the old slot, so I can always refer to the previous one.
Also, my old value was being called when the positive button was clicked, which is at the start of the process flow. So when my timer had expired, the value for the next click is already reached instead of starting at zero again.
Basically the below was being called at the start of the process flow, instead of the end.
sharedPreferences.edit().putLong("addedTagDate", millis).commit();
I figured it out when I put the following line into the very end of the process flow just to make my log read clearer. I realised that my timer variable was being set in the row after the last end point, rather than immediately before the next one.
Log.i(TAG, "*********************************Marker Created******************************");
At last!

Why does the slow task block the other smaller tasks in this program that uses parallel streams?

Following a question form a colleague about parallel streams I wrote the following code to test something out.
public class Test {
public static void main(String args[]) {
List<Runnable> list = new LinkedList<>();
list.add(() -> {
try {
Thread.sleep(10000);
System.out.println("Time : " + System.nanoTime() + " " + "Slow task");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
for (int i = 0; i < 1000; i++) {
int j = i;
list.add(() -> System.out.println("Time : " + System.nanoTime() + " " + j));
}
list.parallelStream().forEach(r -> r.run());
}
}
Strangely the output is always something like the following.
Time : 4096118049370412 61
Time : 4096118049567530 311
Time : 4096118049480238 217
Time : 4096118049652415 405
Time : 4096118049370678 436
Time : 4096118049370575 155
Time : 4096118049720639 437
Time : 4096118049719368 280
Time : 4096118049804630 281
Time : 4096118049684148 406
Time : 4096118049660398 218
TRUNCATED
Time : 4096118070511768 669
Time : 4096118070675678 670
Time : 4096118070584951 426
Time : 4096118070704143 427
Time : 4096118070714441 428
Time : 4096118070722080 429
Time : 4096118070729569 430
Time : 4096118070736782 431
Time : 4096118070744069 432
Time : 4096118070751286 433
Time : 4096118070758554 434
Time : 4096118070765913 435
Time : 4096118070550370 930
Time : 4096118070800538 931
Time : 4096118070687425 671
Time : 4096118070813669 932
Time : 4096118070827794 672
Time : 4096118070866089 933
Time : 4096118070881358 673
Time : 4096118070895344 934
Time : 4096118070907608 674
Time : 4096118070920712 935
Time : 4096118070932934 675
Time : 4096118070945131 936
Time : 4096118070957850 676
Time : 4096118070982326 677
Time : 4096118070991158 678
Time : 4096118070999002 679
Time : 4096118071006501 680
Time : 4096118071017766 681
Time : 4096118071025766 682
Time : 4096118071033318 683
Time : 4096118071070603 684
Time : 4096118071080240 685
Time : 4096128063025914 Slow task
Time : 4096128063123940 0
Time : 4096128063148135 1
Time : 4096128063173285 2
Time : 4096128063176723 3
Time : 4096128063179939 4
Time : 4096128063183077 5
Time : 4096128063191001 6
Time : 4096128063194156 7
Time : 4096128063197273 8
Time : 4096128063200395 9
Time : 4096128063203581 10
Time : 4096128063206988 11
Time : 4096128063210155 12
Time : 4096128063213285 13
Time : 4096128063216411 14
Time : 4096128063219542 15
Time : 4096128063222733 16
Time : 4096128063232190 17
Time : 4096128063235653 18
Time : 4096128063238827 19
Time : 4096128063241962 20
Time : 4096128063245176 21
Time : 4096128063248296 22
Time : 4096128063251444 23
Time : 4096128063254557 24
Time : 4096128063257705 25
Time : 4096128063261566 26
Time : 4096128063264733 27
Time : 4096128063268115 28
Time : 4096128063272851 29
Process finished with exit code 0
That is, there is always some tasks waiting for the slow task to finish processing, even though all the other tasks have finished. I would assume that the slow task should take only one thread and all the other tasks should finish without any problem and only the slow task should take the full 10 seconds. I have 8 CPUs so the parallelism level is 7.
What could the reason be for this?
To add more information, the code is only for understanding purposes. I am not putting it anywhere in production.
There are some limited capabilities when it comes to work-stealing with streams, so if a single thread has pegged itself for some work in other runners, that work will be blocked until it's finished processing other tasks.
You can visualize this by adding a few more debugging notes around your code...
class Test {
public static void main(String[] args) {
List<Runnable> list = new LinkedList<>();
list.add(() -> {
try {
System.out.println("Long sleep - " + Thread.currentThread().getName());
Thread.sleep(10000);
System.out.println("Time : " + System.nanoTime() + " " + "Slow task");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
for (int i = 0; i < 1000; i++) {
int j = i;
list.add(() -> System.out.println("Time : " + System.nanoTime() + " " + j));
}
list.parallelStream().forEach(r -> {
System.out.println(Thread.currentThread().getName());
r.run();
System.out.println();
});
}
}
Upon running this, I observe the following message come up:
Long sleep - ForkJoinPool.commonPool-worker-4
...and about ten seconds later...
Time : 11525122027429 Slow task
ForkJoinPool.commonPool-worker-4
Time : 11525122204035 0
ForkJoinPool.commonPool-worker-4
Time : 11525122245739 1
ForkJoinPool.commonPool-worker-4
Time : 11525122267015 2
ForkJoinPool.commonPool-worker-4
Time : 11525122286921 3
ForkJoinPool.commonPool-worker-4
Time : 11525122306266 4
ForkJoinPool.commonPool-worker-4
Time : 11525122338787 5
ForkJoinPool.commonPool-worker-4
Time : 11525122357288 6
ForkJoinPool.commonPool-worker-4
Time : 11525122376716 7
ForkJoinPool.commonPool-worker-4
Time : 11525122395218 8
ForkJoinPool.commonPool-worker-4
Time : 11525122414165 9
ForkJoinPool.commonPool-worker-4
Time : 11525122432755 10
ForkJoinPool.commonPool-worker-4
Time : 11525122452805 11
ForkJoinPool.commonPool-worker-4
Time : 11525122472624 12
ForkJoinPool.commonPool-worker-4
Time : 11525122491380 13
ForkJoinPool.commonPool-worker-4
Time : 11525122514417 14
ForkJoinPool.commonPool-worker-4
Time : 11525122534550 15
ForkJoinPool.commonPool-worker-4
Time : 11525122553751 16
So this implies that on my box, worker-4 had some work slated for it which couldn't be stolen based on the fact that there were some uneven chunks. Note: if a thread is processing a task in a chunk, that work isn't going to be broken up any further.
[31, 31, 31, 32, 31, 31, 31, 32, 31, 31, 31, 32, 31, 31, 31, 32, 31, 31, 31, 32, 31, 31, 31, 32, 31, 31, 31, 32, 31, 32, 31, 32, 0]
If you were looking for a threading implementation which could steal work from threads which ran longer, it'd be best to use the work-stealing pool directly.
class Test {
public static void main(String[] args) throws InterruptedException {
List<Runnable> list = new LinkedList<>();
list.add(() -> {
try {
System.out.println("Long sleep - " + Thread.currentThread().getName());
Thread.sleep(10000);
System.out.println("Time : " + System.nanoTime() + " " + "Slow task");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
for (int i = 0; i < 1000; i++) {
int j = i;
list.add(() -> {
System.out.println(Thread.currentThread().getName());
System.out.println("Time : " + System.nanoTime() + " " + j);
System.out.println();
});
}
final ExecutorService stealingPool = Executors.newWorkStealingPool();
list.forEach(stealingPool::execute);
stealingPool.shutdown();
stealingPool.awaitTermination(15, TimeUnit.SECONDS);
}
}
The above prints out a more tenable and more reasonable result at the end of the list:
Time : 12210445469314 Slow task
...which implies that all available work has been processed in the time allotted (15 seconds).

Java Spring - manage threads for sync requests

I have Java web application with REST calls using SPRING.
I want to control the number of threads the application is opening for the requests.
So I added Thread config:
package myPackage;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
#Configuration
public class ThreadConfig {
#Bean
public TaskExecutor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(1);
executor.setMaxPoolSize(1);
executor.initialize();
return executor;
}
}
I'm using Sync service not Async, I tested it and it doesn't limit the threads handling the requests, it handles them all at the same time.
What I was expecting is when I send 2 requests at a time - either the 2nd request will be thrown or it will wait until the 1st request will finish.
I'm not implementing Thread in my application at all.
This is the relevant code from my controller:
#RestController
public class Module1Controller {
#RequestMapping(method = RequestMethod.GET, path = "/module1")
InterruptedException {
public Module1 Module1() throws InterruptedException {
Date startDate = new Date();
System.out.println("Thread #: " + Thread.currentThread().getId() + " Request received at: " + startDate);
Thread.sleep(10000);
Date endDate = new Date();
long diff = endDate.getTime() - startDate.getTime();
long seconds = TimeUnit.MILLISECONDS.toSeconds(diff);
System.out.println("Thread #: " + Thread.currentThread().getId() + " thread released at: " + endDate + ", total seconds: " + seconds);
return new Module1(new Clock());
}
This is the console result:
Thread #: 34 Request received at: Sun Dec 17 10:16:20 IST 2017
Thread #: 35 Request received at: Sun Dec 17 10:16:21 IST 2017
Thread #: 34 thread released at: Sun Dec 17 10:16:30 IST 2017, total seconds: 10
Thread #: 35 thread released at: Sun Dec 17 10:16:31 IST 2017, total seconds: 10
What am I missing here?
The problem is that the creation of a TaskExecutor in a configuration bean has no effect on your RestController.
The easiest way to make your RestController process only 1 request at a time is to make the handling method synchronized, e.g. like this:
#RequestMapping(method = RequestMethod.GET, path = "/module1")
public synchronized Module1 getModule1() throws InterruptedException {
If you want a certain maximum number of requests to be processed simultaneously you can use a FixedThreadPool, e.g. like this:
// allow only 2 requests at a time, more requests are automatically placed in a queue
private final ExecutorService es = Executors.newFixedThreadPool(2);
#RequestMapping(method = RequestMethod.GET, path = "/module1")
public Module1 getModule1() throws ExecutionException, InterruptedException {
Future<Module1> result = es.submit(new Callable<Module1>() {
#Override
public String call() throws Exception {
try {
//.... do your work here....
return Module1()
} catch (InterruptedException e) {
return null;
}
}
});
return result.get();
}
I'm not sure why you would want to do this. Limiting the number of requests will result in bad performance and users are not going to like this.
You can not control the threads of request in application instead in container. Maybe you want to run some tasks in limited threads in application. You can do like this:
#RestController
public class ThreadController {
#Autowired
private TaskExecutor taskExecutor;
#RequestMapping(method = RequestMethod.GET, path = "/thread")
public void Module1() {
taskExecutor.execute(new Runnable() {
#Override
public void run() {
Date startDate = new Date();
System.out.println("Thread #: " + Thread.currentThread().getId() +
" Request received at: " + startDate);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Date endDate = new Date();
long diff = endDate.getTime() - startDate.getTime();
long seconds = TimeUnit.MILLISECONDS.toSeconds(diff);
System.out.println("Thread #: " + Thread.currentThread().getId() +
" thread released at: " + endDate + ", total seconds: " + seconds);
}
});
}
}
The result:
Thread #: 55 Request received at: Sun Dec 17 22:40:57 CST 2017
Thread #: 55 thread released at: Sun Dec 17 22:41:07 CST 2017, total seconds: 10
Thread #: 55 Request received at: Sun Dec 17 22:41:16 CST 2017
Thread #: 55 thread released at: Sun Dec 17 22:41:26 CST 2017, total seconds: 10
Thread #: 55 Request received at: Sun Dec 17 22:41:32 CST 2017
Thread #: 55 thread released at: Sun Dec 17 22:41:42 CST 2017, total seconds: 10

How to obtain , record and duration of app usage in minutes , seconds or hours

I have block of code that allows me to retreive all the apps/services running on my android device including the app that I
am building. I am not entirely sure if I am on the right path butbecause I am debugging on android 4.3 I would like to use ActivityManager.RunningService.activeSince
(per service/app) and subtract it from SystemClock.elapsedRealtime(); which I understand is total milliseconds since reboot . So for example
if the device was rebboted at 10am and whatsapp was started at 10:15 and the current time is 1030 I want to be able to use these values
to get an a close estimate of the amount spent on whatsapp. I have a feeling that this is not the most elegant way to achieve this and I am therefore very open to
any advice. This my code below thus far . For now I am using android 4.3
ActivityManager am = (ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> services = am.getRunningServices(Integer.MAX_VALUE);
for (ActivityManager.RunningServiceInfo info : services) {
cal.setTimeInMillis(currentMillis-info.activeSince);
long millisSinceBoot = SystemClock.elapsedRealtime();
long appStartTime = info.activeSince;
long appDuration = appStartTime - millisSinceBoot ;
//long time = ((millisSinceBoot - values.get(position).activeSince)/1000);
//long time = ((millisSinceBoot - currentMillis-info.activeSince)/1000);
//Log.i("HRHHRHRHRHR", "%%%%%%%%%%%%%%%%"+time);
//String time1 = String.valueOf(time);
int seconds = (int) (appDuration / 1000) % 60 ;
int minutes = (int) ((appDuration / (1000*60)) % 60);
int hours = (int) ((appDuration / (1000*60*60)) % 24);
String time11 = hours+":"+minutes+":"+seconds;
Log.i("Time", "Secs:- " + seconds + " " + "Mins:- " + minutes + " " + "Hours:- " + hours);
Log.i(TAG, String.format("Process %s with component %s has been running since %s (%d milliseconds)",
info.process, info.service.getClassName(), cal.getTime().toString(), info.activeSince ));
}

Performance issue in Converting Java object to JSON object

I have tested below example before I do my exact task of converting Java Objects to JSON.
Converting Java objects to JSON with Jackson
And I was looking for the better performance (Converting time should be very less).
This article is showing the stats for the performance in between different APIs from this answer.
My finding was for example with the first link that I mentioned (with few records):
ValueData object = new ValueData();
List<ValueItems> information = new ArrayList<ValueItems>();
ValueItems v1 = new ValueItems(String.valueOf(Calendar.getInstance().getTimeInMillis()), "feat1", 1, "data1");
ValueItems v2 = new ValueItems(String.valueOf(Calendar.getInstance().getTimeInMillis()), "feat2", 2, "data2");
ValueItems v3 = new ValueItems(String.valueOf(Calendar.getInstance().getTimeInMillis()), "feat3", 3, "data3");
ValueItems v4 = new ValueItems(String.valueOf(Calendar.getInstance().getTimeInMillis()), "feat4", 4, "data4");
ValueItems v5 = new ValueItems(String.valueOf(Calendar.getInstance().getTimeInMillis()), "feat5", 5, "data5");
ValueItems v6 = new ValueItems(String.valueOf(Calendar.getInstance().getTimeInMillis()), "feat6", 6, "data6");
ValueItems v7 = new ValueItems(String.valueOf(Calendar.getInstance().getTimeInMillis()), "feat7", 7, "data7");
information.add(v1);
information.add(v2);
information.add(v3);
information.add(v4);
information.add(v5);
information.add(v6);
information.add(v7);
object.setInformation(information);
And I'm going to convert this object by using Jackson:
long smili = Calendar.getInstance().getTimeInMillis();
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);
long emili = Calendar.getInstance().getTimeInMillis();
System.out.println("taken time using jackson = " + (emili - smili) + " milli seconds");
And now I'm doing by using StringBuilder:
smili = Calendar.getInstance().getTimeInMillis();
StringBuilder sb = new StringBuilder();
sb.append("{\n\"information\" : [\n");
for (ValueItems vi : object.getInformation()) {
sb.append("{\n\"timestamp\" : \""+vi.getTimestamp()+"\",");
sb.append("\"feature\" : \""+vi.getFeature()+"\",");
sb.append("\"ean\" : "+vi.getEan()+",");
sb.append("\"data\" : \""+vi.getData()+"\"\n},");
}
sb.deleteCharAt(sb.length() - 1);
sb.append("]\n}");
emili = Calendar.getInstance().getTimeInMillis();
System.out.println("taken time using StringBuilder = " + (emili - smili) + " milli seconds");
I got the timing as given below just for the list size 7:
taken time using jackson = 534 milli seconds
taken time using StringBuilder = 1 milli seconds
I want to convert the object with the information list size more than 10k but the time should be very less.
Creating JSON buy using StringBuilder will help in this case?
Is there other API gives the facility that I require?
Please help me on this.
Thanks Sam B.
I have tried with jakson-afterburner:
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new AfterburnerModule());
ow = mapper.writer().withDefaultPrettyPrinter();
json = ow.writeValueAsString(object);
And I have tested with list sizes 7, 7000, 70000 and 700000:
timing was:
For 7:
taken time using jackson = 217 milli seconds
taken time using StringBuilder = 1 milli seconds
taken time using after-burner = 25 milli seconds
For 7000:
taken time using jackson = 310 milli seconds
taken time using StringBuilder = 31 milli seconds
taken time using after-burner = 65 milli seconds
For 70000:
taken time using jackson = 469 milli seconds
taken time using StringBuilder = 149 milli seconds
taken time using after-burner = 101 milli seconds
For 700000:
taken time using jackson = 1120 milli seconds
taken time using StringBuilder = 705 milli seconds
taken time using after-burner = 623 milli seconds
When the list size increases, afterburner is efficient.

Categories

Resources