Reusable Sample JMeter Scripts

Reusable Sample JMeter Scripts

This blog post aims to be a collection of sample JSR223, Beanshell and other useful reusable scripts. Use them freely in your JMeter projects to leverage the power of JMeter! Reuse them in JSR223 samplers directly as is, or modify them to fit your needs.

Many other example JSR223 samples can be found in our documentation.

Log a Message"This is the log for INFOR level");
log.warn("This is the log for WARNING level");
log.error("This is the log for ERROR level");

Prints a message in the JMeter launch console.


Manipulate a Variable


String my_var = vars.get("MY_VARIABLE");"The value of my_var is " + my_var);

Increment an Integer

int my_number = vars.get("MY_NUMBER").toInteger();
int new_number = 3;
int add = my_number + new_number;
vars.put("MY_NUMBER", add.toString());

Read Write Properties

props.put("PROPERTY_NAME", "VALUE");

//update the existing property

Multiply Function

The following scripts are written in groovy.

def mutiplyTwoNumber = { a,b -> a * b};
//put the function in to JMeter property
props.put("MUTIPLY_TWO_NUMBER", mutiplyTwoNumber);

And later in another script:

//call the function from property (in another Thread Group
def multiplyTwoNumber = props.get("MUTIPLY_TWO_NUMBER");
//check the function to see how it work
def testResult = multiplyTwoNumber(4,5);
//print the log, it should see the value 20"The result of 4 * 5 = " + testResult);

Replace String in a Variable

Replaces characters in a variable and overwrites it.

// Replaces "\/" by "/"

Next Working Day

Computes the next working day into nextworkingday.

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public boolean isWorkingDay(Date date, Calendar calendar) {
  // set calendar time with given date
  int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
  // check if it is Saturday(day=7) or Sunday(day=1)
  if ((dayOfWeek ==  7) || (dayOfWeek == 1)) {
    return false;
  return true;  

Calendar c = Calendar.getInstance();
Date now = new Date();

c.add(Calendar.DAY_OF_WEEK, 1);
while(!isWorkingDay(c.getTime(), c)) {
  c.add(Calendar.DAY_OF_WEEK, 1);
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
vars.put("nextworkingday", df.format(c.getTime()));

Simulate Pacing

Iteration pacing is a good way to make sure every iteration will have the same duration whatever the response time. To implement it, we will use two scripts and a constant variable named “pacing” that contains the duration of the pacing in milliseconds.

Put a first script at the very beginning of your Virtual user profile:


Then the last action in your user profile should be a script with:

import java.util.Map;

Map env = System.getenv();

Stopwatch watch = vars.getObject("watch");
long elapsed = watch.elapsed(java.util.concurrent.TimeUnit.MILLISECONDS);
long pacing = Long.parseLong(vars.get("pacing"));

long sleep = pacing - elapsed;

Note the use of TEST_MODE to ensure the pacing is only used during a real test and not a during a validation.


Computes 36th value of fibonacci series.

int fibonacci(int i) {
   if (i == 1 || i == 2) {
       return i;
   return fibonacci(i - 1) + fibonacci(i - 2);
}"Fibonacci number 36: " + fibonacci(36));

Log Sampler Info

Logs some interesting infos to JMeter log file during the test. "The Sample Label is : " + SampleResult.getSampleLabel() ); "The Start Time in miliseconds is : " + SampleResult.getStartTime() ); "The Response Code is : " + SampleResult.getResponseCode() ); "The Response Message is : " + SampleResult.getResponseMessage() );

Modifying Current SampleResult

The previous sample result can easily be modified by JSR223 scripts.

SampleResult.setSampleLabel("This test is modified by JSR223 script");
def start = System.currentTimeMillis(); //return current time in milliseconds
SampleResult.setStartTime(start); // set StartTime"Start Time should be: " + (new Date(start)).toString()); //print the start time in Date format

SampleResult.setResponseMessage("This is message returned from JSR223 script");
SampleResult.setResponseData("You will see this sentence in Response Data tab", "UTF-8")

Read Previous SampleResult

Reads the previous sample result data from prev variable."Thread Group name is: " + prev.getThreadName());
def end_time = prev.getEndTime()"End Time is: " + (new Date(end_time).toString()));"Response Time is: " + prev.getTime().toString());"Connect Time is: " + prev.getConnectTime().toString());"Latency is: " + prev.getLatency().toString());"Size in bytes is: " + prev.getBytesAsLong().toString());"URL is: " + prev.getURL());"The result is passed: " + prev.isSuccessful().toString());"Headers are: " + prev.getResponseHeaders());

Modify Previous SampleResult

def response_time = prev.getTime().toInteger();
def expected_response_time = 500;
if (response_time > expected_response_time) {
 prev.setSampleLabel("The response time is too long");
 prev.setResponseMessage("The expected response time is : " + expected_response_time + "ms but it took: " + response_time + "ms");

Modify HTTP Request

Define the following script as an Http Sampler pre-processor.


Modify Http Request

JMeter Context

The following script demonstrates the usage of the ctx variable."Current Sampler class is: " + ctx.getCurrentSampler());"JMeter Engine class is: " + ctx.getEngine());"Previous Response Message is: " + ctx.getPreviousResult().getResponseMessage());"Previous Response Code is: " + ctx.getPreviousResult().getResponseCode());"Previous Response URL is: " + ctx.getPreviousResult().getURL());"Previous Response Time is: " + ctx.getPreviousResult().getTime());"Previous Domain is: " + ctx.getPreviousSampler().getDomain());"Previous Protocol is: " + ctx.getPreviousSampler().getProtocol());"Previous Port is: " + ctx.getPreviousSampler().getPort());"Previous Method is: " + ctx.getPreviousSampler().getMethod());"Thread Name is: " + ctx.getThread().getThreadName());"Thread Start Time is: " + ctx.getThread().getStartTime());"Thread End Time is: " + ctx.getThread().getEndTime());"Start Next Thread Loop on Error: " + ctx.getThreadGroup().getOnErrorStartNextLoop());"Stop Test on Error: " + ctx.getThreadGroup().getOnErrorStopTest());

JMeter Context

This is an ever growing base of JMeter scripts. Feel free to come back as we are going to update it every once in a while.

By - CTO.
Tags: Design Jsr223 Logs Response Time



Excellent blog here! Also your web site loads up very fast! What host are you using? Can I get your affiliate link to your host? I wish my website could load up as fast as yours lol

In reply to Vicki

Hi Vicki, OctoPerf’s website is statically generated using Hugo. The content is stored on Amazon S3 and accelerated by CloudFront CDN (which HTTP/2 enabled). We use Gulp to build it. (includes PNG Optimization, CSS and JS Minification etc.) Finally, we use S3_Website to deploy the website to Amazon S3 and refresh CloudFront. (and compress everything using GZIP)


I need how we get the token id from & print by Beanshell I am able to get the token id by regular expression during login. I need to print that token id in next HTTP Request

In reply to rohit

Hi, You can do this by using the script in Manipulate Variables section.

Biju Mani  

This was really helpful and very informative. All in one place. I need one more help. I could not set startTime or endTime using prev or SmpleResult. It throws error in compilation. Actually i want to override the response/load time for a request. Override with a variable value. I tried below but didnt work as I expected. SimpleDateFormat formatter1=new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss.SS”); Date startDate=formatter1.parse(startTime);
Long start = startDate.getTime();“Start Time in Long: " + start); //print the start time in Date format SampleResult.setStartTime(start); // set StartTime“Start Time should be: " + (new Date(start)).toString()); //print the start time in Date format

Date endDate=formatter1.parse(endTime);
Long end = endDate.getTime(); SampleResult.setEndTime(end); // set StartTime“End Time should be: " + (new Date(end)).toString()); //print the start time in Date format

SampleResult.setResponseCode(“200”); SampleResult.createTestSample(start,end); SampleResult.createTestSample(end-start);//To set the elapsed time

I tried creating above script as JSR223 post-processer under HTTP sampler or JDBC sampler. Also tried with JSR223 sampler as well. Can you help me?


Thank you

Your comment has been submitted and will be published once it has been approved.



Your post has failed. Please return to the page and try again. Thank You!


Get our whitepaper,
A beginners guide to performance testing!