Is there a way to speed up my Python code?

import scrypt
import binascii
from passlib.utils.pbkdf2 import get_prf, pbkdf2
from coinkit import BitcoinKeypair

def getWallet(phrase, saltPhrase):
    s1 = scrypt.hash(password=phrase+'\x01', salt=saltPhrase+'\x01', N=1<<18, r=8, p=1, buflen=32)
    s2 = pbkdf2(phrase+'\x02', saltPhrase+'\x02', 1<<16, keylen=32, prf='hmac-sha256')

    key = ''.join(chr(ord(a) ^ ord(b)) for a,b in zip(s1,s2))
    key_hex = binascii.hexlify(key)
    newWallet = BitcoinKeypair(key_hex)
    return {"walletAddress":newWallet.address(), "walletWif":newWallet.wif_pk()}

myWallet = getWallet("ER8FT+HFjk0", "[email protected]")
print "Address: "+myWallet["walletAddress"]+"\nWif: "+myWallet["walletWif"]

To try it you need to install these libraries:

pip install scrypt passlib coinkit

This program generates a Bitcoin Address and the Wif from a phrase, but the problem is that it generates the Output in about 1 second, and that's too long. So i'm looking for a way to speed it up, and if there aren't any solutions, perhaps I could use another programming language?

Thank you.


2 Answers 2


If you're planning on running this repeatedly, you could try running this on PyPy, and see if the JIT starts to speed up some of the regions being run repeatedly. That would be a low-effort way to try to get a performance improvement on long-running code.

Before doing any code changes, profile your current code. That should tell you where the most gains are to be had. Then you could move forward with optimizing with a lot more information.

And, it's possible that doing this in a language with a really good compiler for native machine code would get you faster results. I would tend to think of OCaML in that context, but your milage may vary.


One thing would be to use fastpbkdf2. If you're running passlib >= 1.7, just do pip install fastpbkdf2, and passlib will automatically use it as a backend. That library has a well-optimized C implementation that's noticeably faster than passlib's pure-python builtin. For a tiny bit more speedup, could just call it directly -- while passlib doesn't have much overhead, it's always worth cutting out the middleman when you need the extra speed.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.