Python load test exmaple

Submitted by code_admin on Wed, 09/23/2020 - 09:44

Sample code I can use to base a python load test on.

  1. import datetime
  2. import pytz
  3. import threading
  4.  
  5. def functionToTest():
  6.   # raise Exception("D")
  7.   pass
  8.  
  9. class MyThread(threading.Thread):
  10.   threadNum = None
  11.   numCallsPerThread = None
  12.   numErrors = None
  13.   def __init__(self, threadNum, numCallsPerThread):
  14.     super(MyThread, self).__init__()
  15.     self.threadNum = threadNum
  16.     self.numCallsPerThread = numCallsPerThread
  17.     self.numErrors = 0
  18.  
  19.   def runSingle(self):
  20.     try:
  21.       functionToTest()
  22.     except Exception as err:
  23.       print("Error in thread " + str(self.threadNum) + "\n", err) # for the repr
  24.       # print(str(err)) # for just the message
  25.       # print(err.args) # the arguments that the exception has been called with.
  26.       self.numErrors = self.numErrors + 1
  27.  
  28.   def run(self):
  29.     for curTry in range(0, self.numCallsPerThread):
  30.       self.runSingle()
  31.  
  32. print("Start")
  33.  
  34. numThreadsSTR = input("How many threads?")
  35. numThreads = int(numThreadsSTR)
  36. numCallsPerThreadSTR = input("How many calls in each thread?")
  37. numCallsPerThread = int(numCallsPerThreadSTR)
  38.  
  39. starttime = datetime.datetime.now(pytz.timezone("UTC"))
  40.  
  41. threads = []
  42. for threadNum in range(1, numThreads+1):
  43.   threads.append(MyThread(
  44.     threadNum=threadNum,
  45.     numCallsPerThread=numCallsPerThread
  46.   ))
  47.  
  48. print("Starting all the threads")
  49. for curThread in threads:
  50.   curThread.start()
  51.  
  52. for curThread in threads:
  53.   curThread.join()
  54.  
  55. # Add up the number of errors
  56. numErrors = 0
  57. for curThread in threads:
  58.   numErrors += curThread.numErrors
  59.  
  60. endtime = datetime.datetime.now(pytz.timezone("UTC"))
  61.  
  62. print("---------------------------------------------------------")
  63. print("Treads:", numThreads)
  64. print("Calls per thread:", numCallsPerThread)
  65. print("Errors:", numErrors)
  66. print("Duration (seconds):", '{:6.1f}'.format((endtime-starttime).total_seconds()))
  67. print("End")

Tags

RJM Article Type
Work Notes