2 * Copyright (C) 2007-2012 Argeo GmbH
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org
.argeo
.util
;
18 import java
.text
.NumberFormat
;
19 import java
.text
.ParseException
;
20 import java
.util
.Locale
;
22 public class Throughput
{
23 private final static NumberFormat usNumberFormat
= NumberFormat
24 .getInstance(Locale
.US
);
30 private final Double value
;
31 private final Unit unit
;
33 public Throughput(Double value
, Unit unit
) {
38 public Throughput(Long periodMs
, Long count
, Unit unit
) {
39 if (unit
.equals(Unit
.s
))
40 value
= ((double) count
* 1000d
) / periodMs
;
41 else if (unit
.equals(Unit
.m
))
42 value
= ((double) count
* 60d
* 1000d
) / periodMs
;
43 else if (unit
.equals(Unit
.h
))
44 value
= ((double) count
* 60d
* 60d
* 1000d
) / periodMs
;
45 else if (unit
.equals(Unit
.d
))
46 value
= ((double) count
* 24d
* 60d
* 60d
* 1000d
) / periodMs
;
48 throw new UtilsException("Unsupported unit " + unit
);
52 public Throughput(Double value
, String unitStr
) {
53 this(value
, Unit
.valueOf(unitStr
));
56 public Throughput(String def
) {
57 int index
= def
.indexOf('/');
58 if (def
.length() < 3 || index
<= 0 || index
!= def
.length() - 2)
59 throw new UtilsException(def
+ " no a proper throughput definition"
60 + " (should be <value>/<unit>, e.g. 3.54/s or 1500/h");
61 String valueStr
= def
.substring(0, index
);
62 String unitStr
= def
.substring(index
+ 1);
64 this.value
= usNumberFormat
.parse(valueStr
).doubleValue();
65 } catch (ParseException e
) {
66 throw new UtilsException("Cannot parse " + valueStr
67 + " as a number.", e
);
69 this.unit
= Unit
.valueOf(unitStr
);
72 public Long
asMsPeriod() {
73 if (unit
.equals(Unit
.s
))
74 return Math
.round(1000d
/ value
);
75 else if (unit
.equals(Unit
.m
))
76 return Math
.round((60d
* 1000d
) / value
);
77 else if (unit
.equals(Unit
.h
))
78 return Math
.round((60d
* 60d
* 1000d
) / value
);
79 else if (unit
.equals(Unit
.d
))
80 return Math
.round((24d
* 60d
* 60d
* 1000d
) / value
);
82 throw new UtilsException("Unsupported unit " + unit
);
86 public String
toString() {
87 return usNumberFormat
.format(value
) + '/' + unit
;
90 public Double
getValue() {
94 public Unit
getUnit() {