Last active
March 26, 2022 10:06
-
-
Save acheong08/f550fd062e8c2478edf518386067da52 to your computer and use it in GitHub Desktop.
Threaded CPU benchmark
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Importing modules | |
from time import perf_counter | |
from hashlib import md5 | |
from random import randint | |
from multiprocessing import Pool | |
import sys | |
# Basic function to hash a string | |
def getMD5(plaintext): | |
m = md5() | |
m.update(plaintext.encode('utf-8')) | |
hash = str(m.hexdigest()) | |
return hash | |
# Return number of hashes that can be produced in 10 seconds | |
def getOperations(time): | |
print("Thread started") | |
main_tic = perf_counter() | |
counter = 0 | |
while (perf_counter() - main_tic) < time: | |
getMD5(str(randint(randint(10, 99), (randint(100, 999))))) | |
counter += 1 | |
return counter | |
# Start threads | |
if __name__ == '__main__': | |
threadNum = int(sys.argv[1]) | |
threadTime = int(sys.argv[2]) | |
threads = [] | |
pool = Pool(processes=threadNum) | |
for i in range(threadNum): | |
thread = pool.apply_async(func=getOperations, args=(int(threadTime),)) | |
threads.append(thread) | |
pool.close() | |
pool.join() | |
totalOpers = 0 | |
for thread in threads: | |
result = thread.get() | |
totalOpers += result | |
# Calculate operations per second | |
ops = totalOpers / threadTime | |
print('Average performance: ' + str(ops/1000000) + ' million operations per second.') | |
tps = totalOpers / (threadTime * threadNum) | |
print('Average thread performance: ' + str(tps/1000) + 'k operations per second.') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment