Dynamic Pacing in JMeter using BeanShell

Apache JMeter is a well-designed tool for load generation. It is a freeware tool decorated with almost all the basic and advanced features of a licensed performance testing tool. But certain features are still unavailable like dynamic pacing.

Refer to the article if you want to understand Pacing in detail

Currently, we use either Timers or third-party Thread Groups to control the rate of requests in the Apache JMeter. However, the approach below will help you configure the dynamic pacing in the existing JMeter script without making many changes.

Implementation of Dynamic Pacing using BeanShell

Step 1: Add a BeanShell Sampler before the first transaction or request of the script.

Thread Group (Right Click) -> Add -> Samplers -> BeanShell Sampler

Step 2: Add the below code in the ‘Script’ section of BeanShell Sampler

long start_time = System.currentTimeMillis();
vars.put("ITERATION_START_TIME","" + start_time);

long pacing_time = 60;
vars.put("PACING_TIME","" + pacing_time);

Explanation:

  • start_time: It captures the iteration start time in epoch format
  • ITERATION_START_TIME: It is a variable to save the value of the start time
  • pacing_time: Define the pacing in seconds. In the above example, pacing is defined as 60 seconds.
  • PACING_TIME: It is a variable to save the value of the defined pacing

Best Practice: You can replace the hard-coded value of pacing by defining it in the User Defined Variable and give the variable name in the BeanShell Sampler.

Example: long pacing_time = ${userPacing};

Dynamic Pacing in JMeter using BeanShell

Step 3: Add another BeanShell Sampler after the last transaction or request of the script.

Thread Group (Right Click) -> Add -> Samplers -> BeanShell Sampler

Step 4: Add the below code in the ‘Script’ section of BeanShell Sampler (added in Step 3)

long end_time = System.currentTimeMillis();
String s_start_time = vars.get("ITERATION_START_TIME");
//log.info("s_start_time = " + s_start_time);

long start_time = Long.valueOf(s_start_time);

long iteration_duration_ms = end_time - start_time;

String s_pacing_time = vars.get("PACING_TIME");
//log.info("s_pacing_time = " + s_pacing_time);

long pacing_time_sec = Long.valueOf(s_pacing_time);

long pacing_time_ms = pacing_time_sec * 1000;

long delay_time_ms = pacing_time_ms - iteration_duration_ms;

if (delay_time_ms < 0) {
    delay_time_ms = 0;
}

vars.put("DELAY_TIME","" + delay_time_ms);

Step 5: Add ‘Flow Control Action’ and place it in the last (after Step 3, BeanShell Sampler)

Thread Group (Right Click) -> Add -> Samplers -> Flow Control Action

Dynamic Pacing in JMeter using BeanShell

Step 6: Add the delay time variable name i.e. DELAY_TIME in the pause duration of the Flow Control Action.

Now, you are ready to run your JMeter script with dynamic pacing logic implemented through the BeanShell sampler.


You may be interested:


Leave a Comment