Skip to content

A faster identity function (Trac #1193) #1791

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
thouis opened this issue Oct 19, 2012 · 5 comments
Closed

A faster identity function (Trac #1193) #1791

thouis opened this issue Oct 19, 2012 · 5 comments

Comments

@thouis
Copy link
Contributor

thouis commented Oct 19, 2012

Original ticket http://projects.scipy.org/numpy/ticket/1193 on 2009-08-12 by @kwgoodman, assigned to unknown.

Using a trick that Robert Kern recently posted to the numpy list makes the identity function much faster.

Current version:

def identity(n, dtype=None):
a = array([1]+n*[0],dtype=dtype)
b = empty((n,n),dtype=dtype)
b.flat = a
return b

Proposed version:

def myidentity(n, dtype=None):
a = zeros((n,n), dtype=dtype)
a.flat[::n+1] = 1
return a

timeit identity(1)
100000 loops, best of 3: 14.9 µs per loop
timeit identity(10)
10000 loops, best of 3: 20 µs per loop
timeit identity(100)
1000 loops, best of 3: 696 µs per loop
timeit identity(1000)
10 loops, best of 3: 73.6 ms per loop

timeit myidentity(1)
100000 loops, best of 3: 6.57 µs per loop
timeit myidentity(10)
100000 loops, best of 3: 7.08 µs per loop
timeit myidentity(100)
100000 loops, best of 3: 16.4 µs per loop
timeit myidentity(1000)
100 loops, best of 3: 5.92 ms per loop

It would also speed up the functions that use identity (for example np.linalg.inv).

@thouis
Copy link
Contributor Author

thouis commented Oct 19, 2012

@kwgoodman wrote on 2009-08-12

Sorry, I didn't format the code. Here's the formatted versions:

Current version:

def identity(n, dtype=None):
   a = array([1]+n*[0],dtype=dtype)
   b = empty((n,n),dtype=dtype)
   b.flat = a
   return b

Proposed version:

def myidentity(n, dtype=None):
   a = zeros((n,n), dtype=dtype)
   a.flat[::n+1] = 1
   return a

BTW, is there a way to edit a ticket? I don't see it.

@thouis
Copy link
Contributor Author

thouis commented Oct 19, 2012

Attachment added by @scottza on 2009-08-12: identity.patch

@thouis
Copy link
Contributor Author

thouis commented Oct 19, 2012

@scottza wrote on 2009-08-12

Proposal formatted as a patch against current trunk. No test failures on my system..

@thouis
Copy link
Contributor Author

thouis commented Oct 19, 2012

@charris wrote on 2009-08-12

Fixed in r7303.

@thouis
Copy link
Contributor Author

thouis commented Oct 19, 2012

Milestone changed to 1.4.0 by @charris on 2009-08-12

@thouis thouis closed this as completed Oct 19, 2012
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant