Here are some key in­sights for Python users who want to speed up their code.

OpenSource For You - - LET'S TRY DEVELOPERS -

In most as­pects of our life, speed is im­por­tant—whether it is while driv­ing or ex­e­cut­ing code. Since the dawn of com­puter sci­ence, we have ar­gued about whether our code should use less me­mory or take less time to ex­e­cute. Since the price of me­mory has been steadily de­creas­ing, de­vel­op­ers now fo­cus on mak­ing their code run faster and spend pre­cious hours try­ing to shave those few sec­onds off their ex­e­cu­tion time. But how does one go about try­ing to speed up work­ing code? Well, you could just ran­domly tweak ar­eas of code, but this method has proved WR bH PHssy anG vHry LnHI­fiFLHnW. Usu­ally, , SrHIHr wrLWLng FRGH in Python, but sadly when I get into an ar­gu­ment with some­one about the per­for­mance of Python, the usual re­sponses I get are “Python is too slow,” or “The global in­ter­preter lock re­stricts Python’s code per­for­mance,” or some­thing along those lines. So my goals for writ­ing this ar­ti­cle are as fol­lows: Get­ting faster code us­ing pure Python. To list some tech­niques and tools you can use with­out re­sort­ing to writ­ing code in C or as­sem­bly. Here is the list of li­braries that the re­quired tools de­pend on, so down­load and in­stall them, if you haven’t al­ready done so: CPython (The de­fault in­ter­preter) lLnHBSrR­filHr Run­snake

Let's get started by look­ing at some code! This is the same code we will try to im­prove in sub­se­quent por­tions of the ar­ti­cle, and it's the bor­ing old ma­trix mul­ti­pli­ca­tion code Em~trix_­multKpy): im­port random from time im­port * im­port cPro­file class ma­trix(ob­ject): def __init__(self, m, n):

# Cre­ate random ma­trix self.m m self.n n self.mat in range(m)]

[[random.random() for row in range(n)] for col def zero(self):

self.mat [[0 for row in range(self.n)] for col in range(self.m)] def mult(ma­trix1, ma­trix2):

# Ma­trix mul­ti­pli­ca­tion

Newspapers in English

Newspapers from India

© PressReader. All rights reserved.