01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: *
17: */
18:
19: package org.apache.jmeter.util;
20:
21: /**
22: *
23: * Generate appropriate pauses for a given CPS (characters per second)
24: */
25: public class CPSPauser {
26: private final int CPS; // Characters per second to emulate
27:
28: // Conversions for milli and nano seconds
29: private static final int MS_PER_SEC = 1000;
30: private static final int NS_PER_SEC = 1000000000;
31: private static final int NS_PER_MS = NS_PER_SEC / MS_PER_SEC;
32:
33: /**
34: * Create a pauser with the appropriate speed settings.
35: *
36: * @param cps CPS to emulate
37: */
38: public CPSPauser(int cps) {
39: if (cps <= 0) {
40: throw new IllegalArgumentException("Speed (cps) <= 0");
41: }
42: CPS = cps;
43: }
44:
45: /**
46: * Pause for an appropriate time according to the number of bytes being transferred.
47: *
48: * @param bytes number of bytes being transferred
49: */
50: public void pause(int bytes) {
51: long sleepMS = (bytes * MS_PER_SEC) / CPS;
52: int sleepNS = ((bytes * MS_PER_SEC) / CPS) % NS_PER_MS;
53: try {
54: Thread.sleep(sleepMS, sleepNS);
55: } catch (InterruptedException ignored) {
56: }
57: }
58: }
|