# Collection of code snippets by Arne Vajhøj 
# (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import sys
import time
import math

def printres(t1, t2, n1, n2, ops):
    xperf = n1 * n2 / (t2 - t1)
    print('%.4f million %s per second' % (xperf / 1000000, ops))

NINT = 10000
NFP = 10000
NSTR = 10000
N = 10000

def testint(scale):
    nintscale = NINT // scale
    t1 = time.time()
    for i in range(nintscale):
        sum = i
        for j in range(N):
            sum = ((sum + 1) * 2 + 1) // 2
        if sum != (i + N):
            print('Integer test error')
            sys.exit(0)
    t2 = time.time()
    printres(t1, t2, nintscale, N, 'integer operations')

def testfp(scale):
    nfpscale = NFP // scale
    t1 = time.time()
    for i in range(nfpscale):
        sum = i
        for j in range(N):
            sum = ((sum + 1.0) * 2 + 1) / 2
        if math.fabs(sum - (i + 1.5 * N)) > 1:
            print('Floating point test error')
            sys.exit(0)
    t2 = time.time()
    printres(t1, t2, nfpscale, N, 'floating point operations')

ALFA = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
VMS_FACTOR = 100

def teststr(scale):
    nstrscale = NSTR // scale
    t1 = time.time()
    for i in range(nstrscale * VMS_FACTOR):
        sb = ''
        for j in range((N // VMS_FACTOR) // 10):
            realj = 10 * j
            s = ALFA + ALFA
            ix = (i + j) % len(ALFA)
            sb = sb + s[ix:ix+1] + s[ix+1:ix+3] + s[ix+3:ix+6] + s[ix+6:ix+10]
        ix1 = (N // VMS_FACTOR) // 3
        ix2 = 2 * (N // VMS_FACTOR) // 3
        mix1 = (i + ix1) % len(ALFA)
        mix2 = (i + ix2) % len(ALFA)
        if len(sb) != (N // VMS_FACTOR) or sb[ix1:ix1] != ALFA[mix1:mix1] or sb[ix2:ix2] != ALFA[mix2:mix2]:
            print('String test error')
            sys.exit(0)
    t2 = time.time()
    printres(t1, t2, nstrscale, N // 10, 'string operations')

REP = 10

print('Python:')
if len(sys.argv) > 1:
    scale = int(sys.argv[1])
else:
    scale = 1
for i in range(REP):
    testint(scale)
for i in range(REP):
    testfp(scale)
for i in range(REP):
    teststr(scale)

