Skip to content

Instantly share code, notes, and snippets.

@tkamishima
Created July 26, 2011 12:51
Show Gist options
  • Save tkamishima/1106678 to your computer and use it in GitHub Desktop.
Save tkamishima/1106678 to your computer and use it in GitHub Desktop.
Perfomance comparison between np.sum vs np.count_nonzero
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import timeit
import sys
import numpy as np
SAMPLE = 10000
REP = 5
a = np.random.randn(SAMPLE, SAMPLE)
def test_sum():
""" np.sum """
r = np.sum(a > 0.0)
# print r
def test_count():
""" count_nonzero """
r = np.count_nonzero(a > 0.0)
# print r
if __name__ == '__main__':
t = timeit.Timer("test_sum()", "from __main__ import test_sum")
try:
print >> sys.stderr, "sum:", t.timeit(REP)
except:
t.print_exc()
t = timeit.Timer("test_count()", "from __main__ import test_count")
try:
print >> sys.stderr, "cnt:", t.timeit(REP)
except:
t.print_exc()
@tkamishima
Copy link
Author

sum: 2.10800409317
cnt: 3.04244184494

@NegriAndrea
Copy link

With 20000:

sum: 4.14537286758
cnt: 2.55795407295

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment