Different runtimes for np.uint8 and np.int8

I have this piece of code:

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

import time
import numpy as np

for t in [np.uint8, np.int8]:
  a=np.empty([480, 640], t)
  v=[10, 245]
  for y in range(480):
    for x in range(640):
      a[y, x]=v[x&1]  # 50%=10, 50%=245
  t1=time.clock()
  a[a<32]=0
  a[a>224]=0
  t2=time.clock()
  print("%2.3f ms"%((t2-t1)*1000), a.dtype)

And I get this output:

3.162 ms uint8
0.329 ms int8

Why is this one a[a<32]=0ten times faster if it runs on a signed array?

Is there a way to speed it up on an unsigned array?

And yes ... it's the same with a lot of samples:

for t in [np.int8, np.uint8]:
  a=np.empty([480, 640], t)
  v=[10, 245]
  for y in range(480):
    for x in range(640):
      a[y, x]=v[x&1]  # 50%=10, 50%=235

  t1=time.process_time()
  for l in range(1000):
    b=1*a  # deep copy
    b[b<32]=0
    b[b>224]=0
  t2=time.process_time()
  print("%5.4f ms"%((t2-t1)*1000), a.dtype)

Result:

328.0701 ms int8
3081.5300 ms uint8
+4
source share
1 answer

Just to make sure everyone knows where the time difference comes from, I broke the code before every single step:

Whole code

%%timeit 
tmp = np.array(a, dtype=np.uint8, copy=True)
tmp[tmp < 30] = 0
tmp[tmp > 224] = 0

10 loops, best 3: 21.6 ms per cycle

%%timeit 
tmp = np.array(a, dtype=np.int8, copy=True)
tmp[tmp < 30] = 0
tmp[tmp > 224] = 0

100 cycles, best 3: 10.4 ms per cycle

So, the whole operation is faster, but let's look at the time spent in each installation operation :

%timeit tmp = np.array(a, dtype=np.uint8, copy=True); tmp[tmp < 30] = 0
tmp = np.array(a, dtype=np.uint8, copy=True)
tmp[tmp < 30] = 0
%timeit tmp2 = np.array(tmp, copy=True); tmp2[tmp2 > 224] = 0

100 , 3: 19,3

100 , 3: 17,6

, int8:

100 , 3: 6,75

100 , 3: 4,36

, , , :

%timeit tmp = np.array(a, dtype=np.uint8, copy=True); _ = tmp[tmp < 30]
tmp = np.array(a, dtype=np.uint8, copy=True)
tmp[tmp < 30] = 0
%timeit tmp2 = np.array(tmp, copy=True); _ = tmp2[tmp2 > 224]

100 , 3: 17,9

100 , 3: 16,2

int8:

100 , 3: 7,64

100 , 3: 4,3

int . :

%timeit tmp = np.array(a, dtype=np.uint8, copy=True); _ = tmp < 30
tmp = np.array(a, dtype=np.uint8, copy=True)
tmp[tmp < 30] = 0
%timeit tmp2 = np.array(tmp, copy=True); _ = tmp2 > 224

100 , 3: 4,25

100 , 3: 2,58

int8:

100 , 3: 4,26

100 , 3: 4,08

: dtype , , int. , numpy , all ( 235 -21 in int8) no. . uint True, False ().

: numpy / .

v=[10,100] uint, , , :

uint: 10 loops, best of 3: 21.7 ms per loop
int:  10 loops, best of 3: 23.2 ms per loop

, , numpy , all/no element. False, numpy uint int.

+1

All Articles