"""Test GIL mechanism speed. Adjust CheckInterval, keeping it small so GIL unlocks/locks/blocks take a majority of a thread's time. """ import sys, threading, time, random ThreadCount = 4 CheckInterval = 1 WorkIterations = (500, 1000) RunsPerThread = 100 Seed = 123456 # -- ThreadsDone = threading.Semaphore(0) RateSum = 0.0 def WorkerThread(Iterations): global RateSum RunNum = RunsPerThread clock = time.clock sleep = time.sleep try: TimeTotal = clock() while RunNum: Iter = Iterations while Iter: Iter -= 1 RunNum -= 1 TimeTotal = clock() - TimeTotal TimeTotal /= RunsPerThread * Iterations RateSum += TimeTotal finally: ThreadsDone.release() def Run(): global RateSum IterMin, IterMax = WorkIterations IterScale = IterMax - IterMin sys.setcheckinterval(CheckInterval) random.seed(Seed) if ThreadCount == 1: WorkerThread(int(IterMin + random.random()*IterScale)) else: for N in xrange(ThreadCount): IterN = int(IterMin + random.random()*IterScale) T = threading.Thread(target=WorkerThread, args=(IterN,)) T.setDaemon(False) T.start() Done = 0 while 1: ThreadsDone.acquire() Done += 1 sys.stdout.write(".") sys.stdout.flush() if Done == ThreadCount: break print RateSum /= float(ThreadCount) Nsec = RateSum*1000.0*1000.0*1000.0 # nanoseconds print "%07.03f ns/iter" % Nsec if __name__ == "__main__": Run()