Jump to content

Only in Python ...

Herr.Hoefkens

642 views

Not to take a piss on python , i actually like the languagee , especially the development speed you get with it.

but...

only in python are things that are an order of magnitude faster in other languages actually much much slower:

 

Branching logic vs Branchless Logic:

import random
from time import perf_counter_ns,sleep

testnrs = [random.randrange(0,5,1) for _ in range(2**20)]

def branch(nr,idx,result):
	if nr < 1 :
		result|=int((str(abs(result))*9)[1:3])
	elif nr == 1:
		result|=idx
	elif nr == 2:
		result|= 2*int(str(result)[0])
	elif nr == 3 :
		result|=3*idx
	elif nr >= 4 :
		result|= nr*int(str(idx)[-1])
	return result


def nobranch(nr,idx,result):
	result|= (((int((str(abs(result))*9)[1:3])) * (nr < 1)) + (
						(idx)*(nr==1)) + (
						(2*int(str(result)[0])*(nr==2))) +(
						((3*idx)*(nr==3)))+ (
						(nr*int(str(idx)[-1])*(nr>=4))))
	return result

subtot1=0 ;start1=perf_counter_ns()
for idx,nr in enumerate(testnrs):	subtot1=branch(nr,idx,subtot1)
time1=(perf_counter_ns()-start1)*10**-9

sleep(2)

subtot2=0 ; start2=perf_counter_ns()
for idx,nr in enumerate(testnrs):	subtot2=nobranch(nr,idx,subtot2)
time2=(perf_counter_ns()-start2)*10**-9

print(subtot1,'\t\ttime:\t\t',time1)
print(subtot2,'\t\ttime:\t\t',time2)

result:

4194303 	:	time:		 3.047605361
4194303 	:	time:		 9.314754315

 

0 Comments

There are no comments to display.

×