1 /**********************************************************************
2 * Copyright (c) 2015, 2016 Ericsson
4 * All rights reserved. This program and the accompanying materials are
5 * made available under the terms of the Eclipse Public License v1.0 which
6 * accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
8 **********************************************************************/
10 package org
.eclipse
.tracecompass
.analysis
.timing
.ui
.views
.segmentstore
;
12 import java
.text
.DecimalFormat
;
13 import java
.text
.FieldPosition
;
14 import java
.text
.Format
;
15 import java
.text
.ParsePosition
;
17 import org
.eclipse
.jdt
.annotation
.Nullable
;
18 import org
.eclipse
.tracecompass
.common
.core
.NonNullUtils
;
21 * Time format, it will take a time in nano seconds and convert it to a string
22 * with 3 decimals max.
26 * <li>100 -> "100 ns"</li>
27 * <li>1001 -> "1.001 us" (mu)</li>
28 * <li>314159264 -> "312.159 ms"</li>
29 * <li>10000002000000 -> "1000.002 s"</li>
32 public final class SubSecondTimeWithUnitFormat
extends Format
{
35 private static final long serialVersionUID
= -5147827135781459548L;
37 private static final String SECONDS
= "s"; //$NON-NLS-1$
38 private static final String NANOSECONDS
= "ns"; //$NON-NLS-1$
39 private static final String MILLISECONDS
= "ms"; //$NON-NLS-1$
40 private static final String MICROSECONDS
= "\u00B5" + SECONDS
; //$NON-NLS-1$
42 private static final int NANOS_PER_SEC
= 1000000000;
43 private static final int NANOS_PER_MILLI
= 1000000;
44 private static final int NANOS_PER_MICRO
= 1000;
46 private final DecimalFormat fDecimalFormat
= new DecimalFormat("#.###"); //$NON-NLS-1$
49 public Object
parseObject(@Nullable String source
, @Nullable ParsePosition pos
) {
50 return source
== null ?
"" : source
; //$NON-NLS-1$
54 public StringBuffer
format(@Nullable Object obj
, @Nullable StringBuffer toAppendTo
, @Nullable FieldPosition pos
) {
55 final @Nullable StringBuffer appender
= toAppendTo
;
56 if ((obj
!= null) && (obj
instanceof Double
|| obj
instanceof Long
)) {
57 double formattedTime
= obj
instanceof Long ?
((Long
) obj
).doubleValue() : ((Double
) obj
).doubleValue();
58 String unit
= NANOSECONDS
;
59 if (formattedTime
> NANOS_PER_SEC
) {
61 formattedTime
/= NANOS_PER_SEC
;
62 } else if (formattedTime
> NANOS_PER_MILLI
) {
64 formattedTime
/= NANOS_PER_MILLI
;
65 } else if (formattedTime
> NANOS_PER_MICRO
) {
67 formattedTime
/= NANOS_PER_MICRO
;
69 String timeString
= fDecimalFormat
.format(formattedTime
);
70 return appender
== null ?
new StringBuffer() : NonNullUtils
.checkNotNull(appender
.append(timeString
).append(' ').append(unit
));
72 return new StringBuffer();