Showing posts with label performance. Show all posts
Showing posts with label performance. Show all posts

Wednesday, September 19, 2018

Reverse slider when swiped down

Leave a Comment

I followed this article for a vertical swipeable cards slider.

This question has two parts.

1. I cant understand on how to reverse the direction of slider when swiped down?

Here is the relevant codepen - https://codepen.io/bmarcelino/pen/vRYPXV

The relevant function to update the cards

function updateUi() {     requestAnimationFrame(function(){         elTrans = 0;         var elZindex = 5;         var elScale = 1;         var elOpac = 1;         var elTransTop = items;         var elTransInc = elementsMargin;          for(i = currentPosition; i < (currentPosition + items); i++){             if(listElNodesObj[i]){                 listElNodesObj[i].classList.add('stackedcards-bottom', 'stackedcards--animatable', 'stackedcards-origin-bottom');                  listElNodesObj[i].style.transform ='scale(' + elScale + ') translateX(0) translateY(' + (elTrans - elTransInc) + 'px) translateZ(0)';                 listElNodesObj[i].style.webkitTransform ='scale(' + elScale + ') translateX(0) translateY(' + (elTrans - elTransInc) + 'px) translateZ(0)';                 listElNodesObj[i].style.opacity = elOpac;                 listElNodesObj[i].style.display = 'block';                 listElNodesObj[i].style.zIndex = elZindex;                  elScale = elScale - 0.04;                 elOpac = elOpac - (1 / items);                 elZindex--;             }         }      });  }; 

I am not particularly well versed in Javascript.
As of now the slider moves in only one direction when swiped - forward. I am looking to understand an implementation of adding the backward movement to the slider.

2. Regarding performance

Also, requestAnimationFrame really helps out in providing a smooth experience while swiping. But is there a limit as to how many cards should be in DOM? I will be calling an API service to get the contents, since it will return media, so will simply setting opacity to 0 help out in any way reducing memory use?

The author argues that removing DOM would force the browser to repaint, which can impact performance substantially? But isn't that virtual list do? What is the performance to cost ratio in such scenarios?

2 Answers

Answers 1

This is not going to be a complete answer but seeing as no one else has responded I'll give answering part 1 of your question a shot. Note that this is just an example to help you understand how to make the cards go backwards not a production ready solution.

To rewire the "Top" button to go backwards, you just need to make the following changes:

  • In onSwipeTop() change currentPosition = currentPosition + 1; to currentPosition = currentPosition - 1;
  • Also in onSwipeTop() change transformUi(0, -1000, 0, topObj); to transformUi(0, 0, 0, topObj);. This hides the card going up animation.
  • In updateUi() change i < (currentPosition + items) to i <= (currentPosition + items). This fixes a bug where only two of the three cards are updated.

Now try clicking Left or Right a couple times then click Top a couple times. Each time you click Top you should see a card come back.

Presumably you'll want to make a new button "Bottom" instead of rewiring "Top" and you'll probably also want to put limits on changes to currentPosition so you can't go beyond the first/last card but this should at least get you started.

I hope this helps.

Answers 2

Reversing the slider

Following is a very brief explanation of how the script works, including a suggestion for getting it to reverse the direction and 'unswipe' cards. The reverse direction method was inspired by Rocky's excellent answer - he deserves full credit for the idea.

  1. Once the document is loaded the script gets a list of all available cards. In your example the cards are hard coded elements in the DOM, and the list of cards, listElNodesObj, is a list of those elements. This is important to remember: the cards are not an abstraction, they are fundamentally elements within the page. When you add media and data to your cards you will have to do so by attaching it to elements in the DOM (e.g. with data attributes).

  2. The script gets the current card index called currentPosition; to begin with this is the top card. It then displays the current card and the two cards behind it (currentPosition + 1 and currentPosition + 2).

  3. On an input the card is appropriately animated to fly off the left, right or top. The current card index is incremented by one, advancing by one into the stack. The new current card and the two cards behind it are displayed.

At the moment all actions - swipe left, right and top - all advance into the stack. To reverse the direction you need to listen for a new action (or repurpose a current one such as swipe top), and on that action the current card index is decremented by 1. Add a check for less than zero. currentPosition = Math.max( 0, currentPosition - 1 );

Rocky has answered with an excellent solution that implements this.

Now this implementation begins with all cards already present in the DOM. You appear to want to update your stack of cards from a backend API. To do this you need a way of popping the card off one end and adding a new one on the other end when swiping. As stated above your list of cards is tied very closely to the DOM so you will need to abstract it a little to achieve this. Create a list of elements that you fill from your API and populate your initial document with it (instead of the other way around). When you swipe, whether forwards or back, pop an element off the receding end and add a new element, populated from your API, to the advancing end. Interestingly both your list size and your current position will always stay the same.

If your current position is always one back from the top-most card, and the last card in the stack is one more than the last visible card, you will always have a card ready to animate into view.

Performance

A slight clarification of terms here: Altering something like opacity causes a repaint, removing an element from the DOM, whether soft or hard removal, causes a reflow. Repaints are expensive because the browser must check the visibility of every element in the DOM; reflows are even more expensive because the layout must be recalculated. See What's the difference between reflow and repaint?

There are two ways you could limit the number of cards in the DOM. You could set display: none which leaves it in memory and the DOM, but prevents the browser from considering it when reflowing or repainting. Or you could use parent.appendChild(child) to add a card and parent.removeChild(child) to remove the card, ensuring that no reference to that element exists in JavaScript once it's removed, and once the garbage collector runs the removed element will be physically removed from memory. Both will trigger a reflow. Elements with opacity: 0 will remain fully in the DOM for reflowing and repainting.

As to what gives the best performance: changing the opacity or removing from memory, that really depends on your implementation. I can give you a few relevant pointers though.

Memory constraints "Is there a limit as to how many cards should be in DOM?" Absolutely, but this depends on your data. If you have a very small total amount of cards you could indeed load them all at the beginning and hide swiped ones with opacity: 0 or display: none. The animation fluidity might even be improved (see point on animation blocking computations below). The performance difference purely from higher memory use will almost certainly be unnoticeable as modern browsers have oodles of memory and will stop your script well before it needs pagefile or swap. If you really will have such a huge DOM in memory that performance would noticeably degrade, your content download time would be a much bigger issue.

However, much more to the point, you rightly ask if removing or adding elements is the whole point of a virtual list. Why keep an element in memory if you will never access it again, or why load an element that is so far down the list it may never be reached. Indeed you state that you will be accessing content from an API which strongly implies you'll be accessing the card content one at a time. Waiting till you have all the content from your API may take a very noticeable length of time; as you already seem to be aware it would provide a better experience to only access the cards that you need to fill a fixed size list. (If you intend to reverse the direction of the slider then you should keep at least one swiped card in memory so that when swiping back you aren't ruining the animation by pausing or sending an empty card as you wait to download the content)

Animation Blocking Computations Download times aside, the real performance advantage of display: none and opacity: 0 for cards that are swiped or are too far back in the list is that their content is already present in the DOM. (And as stated above, opacity: 0 has one further advantage: it does not trigger a reflow). By comparison physically adding and removing elements from the DOM requires an extra computation, namely inserting or removing the card node and all its children in the DOM tree. If this is done synchronously then you will have an animation blocking computation, whereby the swipe animation cannot take place until the DOM tree update is completed.

However let's keep things in perspective. Firstly, adding and removing nodes from the DOM tree is typically extremely fast. innerHTML has been demonstrated to be marginally faster at adding to the DOM but much slower at removing, so pick your poison with care. But unless you're adding tens or hundreds of kilobytes of data to your cards, the operation will likely take less than a millisecond. Secondly, you state that you will be retrieving content for the list from an API, which implies an asynchronous connection. If you take care when constructing your asynchronous functions, your function to add content to the DOM will not necessarily interfere with the animation. (Not to imply that JavaScript is multi-threaded; it is single threaded but well constructed asynchronous code means the order in which functions are executed does not matter). If the cards being added or removed are done so when an animation is not queued, any performance hit will become both shorter and less perceivable.

Finally, every DOM manipulation is a new render update so you want to do as few manipulations as possible. You would therefore create the elements against each other in memory and only at the very end insert the highest element into the DOM. See Fastest DOM insertion . If you can contain all card data within that card then each swipe would require just two DOM manipulations. It depends on what media the cards contain, but it's conceivable that, at worst, adding and removing cards to the stack will take only tens of milliseconds in combined time.

GPU Most rendering engines have access to a GPU which can achieve far better efficiency than the CPU in drawing and compositing operations that involve large numbers of pixels. Render layers are not rendered with the GPU by default. The page GPU Accelerated Compositing in Chrome states,

While in theory every single RenderLayer could paint itself into a separate backing surface [i.e. a GPU accessible compositing layer], in practice this could be quite wasteful in terms of memory (VRAM especially).

To ensure an animation such as opacity change is rendered using the GPU, you need to access the animation in such a way that it is implicitly composited. The above page has a comprehensive list of how to do this, but essentially you'd use CSS animations to change opacity which prompts the browser to promote the element to a compositing layer. The current code you have presented uses JavaScript to update opacity each animation frame, thus the opacity change is not a candidate for implicit compositing. (You appear to be using 3D transforms for the movement animation which triggers implicit compositing, so that is likely already GPU optimised). Changing the code to use CSS animations is not a trivial task, but it would very likely improve performance, specifically the frame rate during animation. Of course bench-marking is required to verify this for your specific scenario, see https://www.smashingmagazine.com/2016/12/gpu-animation-doing-it-right/ for a discussion on why some GPU animations may run slower.


In summary, the performance increase due to dynamically adding and removing elements from the virtual list, while potentially marginally higher than having the entire list fully loaded, is likely to be only a extra few milliseconds per swipe. With an asynchronous implementation, the frame rate during the animation should not change. This should normally be an easy concession for the likely large savings in initial download time, but must be considered in conjunction with other details of your particular implementation.

Read More

Monday, August 13, 2018

Curious memory consumption of pandas.unique()

Leave a Comment

While profiling the memory consumption of my algorithm, I was surprised that sometimes for smaller inputs more memory was needed.

It all boils down to the following usage of pandas.unique():

import numpy as np import pandas as pd import sys  N=int(sys.argv[1])  a=np.arange(N, dtype=np.int64) b=pd.unique(a) 

with N=6*10^7 it needs 3.7GB peak memory, but with N=8*10^7 "only" 3GB.

Scanning different input-size yields the following graph:

enter image description here

Out of curiosity and for self-education: How can the counterintuitive behavior (i.e. more memory for smaller input size) around N=5*10^7, N=1.3*10^7 be explained?


Here are the scripts for producing the memory consumption graph on Linux:

pandas_unique_test.py:

import numpy as np import pandas as pd import sys  N=int(sys.argv[1])     a=np.arange(N, dtype=np.int64) b=pd.unique(a) 

show_memory.py:

import sys import matplotlib.pyplot as plt    ns=[] mems=[] for line in sys.stdin.readlines():     n,mem = map(int, line.strip().split(" "))     ns.append(n)     mems.append(mem) plt.plot(ns, mems, label='peak-memory') plt.xlabel('n') plt.ylabel('peak memory in KB') ymin, ymax = plt.ylim() plt.ylim(0,ymax) plt.legend() plt.show() 

run_perf_test.sh:

WRAPPER="/usr/bin/time -f%M" #peak memory in Kb N=1000000 while [ $N -lt 100000000 ] do    printf "$N "    $WRAPPER python pandas_unique_test.py $N    N=`expr $N + 1000000` done  

And now:

sh run_perf_tests.sh  2>&1 | python show_memory.py 

1 Answers

Answers 1

Let's see...

pandas.unique says it's a "hash-table based unique".

It calls this function to acquire the correct hash table implementation for your data, namely htable.Int64HashTable.

The hash table is initialized with size_hint = the length of your value vector. That means kh_resize_DTYPE(table, size_hint) gets called.

Those functions are defined (templated) here in khash.h.

It seems to allocate (size_hint >> 5) * 4 + (size_hint) * 8 * 2 bytes of memory for the buckets (maybe more, maybe less, I might be off here).

Then, HashTable.unique() is called.

It allocates an empty Int64Vector, which seem to quadruple their size whenever they get filled, starting from 128.

It then iterates over your values, figuring out whether they're in the hash table; if not, they get added to both the hash table and the vector. (This is where the vector may grow; the hash table shouldn't need to grow due to the size hint.)

Finally, a NumPy ndarray is made to point at the vector.

So uh, I think you're seeing the vector size quadrupling at certain thresholds (which should be, if my late-night math stands,

>>> [2 ** (2 * i - 1) for i in range(4, 20)] [     128,     512,     2048,     8192,     32768,     131072,     524288,     2097152,     8388608,     33554432,     134217728,     536870912,     2147483648,     8589934592,     34359738368,     137438953472,     ..., ] 

Hope this sheds some light at things :)

Read More

Monday, June 25, 2018

.net core perf profiler via code

Leave a Comment

I developed a middleware that starts a Stopwatch before invoking next and stops when the response is available, I do log the elapsed time after that.

This is all good. But it doesnt provide me breakdown, ie: within the call which method invocations took how much? for example: if I have 4 method calls in a request, I would like to know each one's duration.

I assume, middleware is not enough for this purpose, without having to put decorators all over the place, how can i get this done?

Thanks.

1 Answers

Answers 1

Probably, you have to manually instrument most interesting pieces of code.

Although, there are solutions for IL injection (see MSIL Injection page on PostSharp website), I don't think that it is possible to inject code in arbitrary places without changing existing code base. However, in many cases it is relatively easy to instrument large portion of existing code (given it is reasonably well separated into modules) using decorators. For example add custom profiling DelegatingHandler to HttpClient or use profiling SqlConnection factory.

In order to inspect call hierarchy and latency you can utilize MiniProfiler, it's built-in decorators and RenderPlainText() method. Or you can utilize Metrics.NET library to inspect throughput related metrics such as histogram and counter.

Read More

Thursday, June 7, 2018

Sort string with integers and words without any change in their positions

Leave a Comment

Say I have a string a.

a = "12 I have car 8 200 a" 

I need to sort this string in such a way that the output should be

8 a car have 12 200 I 

ie, Sort the string in such a way that all words are in alphabetical order and all integers are in numerical order. Furthermore, if the nth element in the string is an integer it must remain an integer, and if it is a word it must remain a word.

This is what I tried.

a = "12 I have car 8 200 a"   def is_digit(element_):     """     Function to check the item is a number. We can make using of default isdigit function     but it will not work with negative numbers.     :param element_:     :return: is_digit_     """     try:         int(element_)         is_digit_ = True     except ValueError:         is_digit_ = False      return is_digit_    space_separated = a.split()  integers = [int(i) for i in space_separated if is_digit(i)] strings = [i for i in space_separated if i.isalpha()]  # sort list in place integers.sort() strings.sort(key=str.lower)  # This conversion to iter is to make use of next method. int_iter = iter(integers) st_iter = iter(strings)  final = [next(int_iter) if is_digit(element) else next(st_iter) if element.isalpha() else element for element in          space_separated]  print " ".join(map(str, final)) # 8 a car have 12 200 I 

I am getting the right output. But I am using two separate sorting function for sorting integers and the words(which I think is expensive).

Is it possible to do the entire sorting using a single sort function?.

6 Answers

Answers 1

numpy allows to write it more concisely, though doesn't eliminate the need for two separate sorts:

$ python3 Python 3.5.2 (default, Nov 23 2017, 16:37:01)  [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import numpy as np >>> from numpy.core.defchararray import isdecimal, lower >>>  >>> s = "12 I have car 8 200 a" >>>  >>> a = np.array(s.split()) >>>  >>> integer_mask = isdecimal(a) >>> string_mask = ~integer_mask >>> strings = a[string_mask] >>>  >>> a[integer_mask] = np.sort(np.int_(a[integer_mask])) >>> a[string_mask]  = strings[np.argsort(lower(strings))] >>>  >>> ' '.join(a) '8 a car have 12 200 I' 

Answers 2

Is it possible to do the entire sorting using a single sort function?.

No, not really.

Why not? It turns out the answer is already in your code.

integers.sort() strings.sort(key=str.lower) 

Notice how you need to sort by two different functions here. The first is an integer sort, the second is a lowercase string sort. We could try something like this:

def get_sort_order(element):     try:         value = int(element)     except ValueError:         value = element.lower()     return value  a.sort(key=get_sort_order) 

But that doesn't work either; it just gives us the result

['8', '12', '200', 'a', 'car', 'have', 'I'] 

You could probably force this into a solution, but it isn't going to be pretty.

However, there is another point I'd like to address:

But I am using two separate sorting function for sorting integers and the words (which I think is expensive).

Sorting two distinct lists is basically always going to be faster anyway. To find out why, just look at the time complexity of the two tasks:

Assuming a list of length 1000, exactly half integer and half strings, and a sorting algorithm of O(nlog(n)):

One single sort: 1000 * log(1000) = 3000

Two separate sorts: 2 * (500 * log(500) = ~2699

So sorting the list in a single run is both more difficult to implement and slower!

Answers 3

It is possible in one sort, by applying a custom function within the 'sorted' method as a User described above. I have tried a simplified version for the same. The default 'sorted' method does the wonder with a little tweak. Hope it resolves your query.

import re  input = "12 I have car 8 200 a" splitted = input.split() s_lst=sorted(splitted, key=lambda a:int(a) if a.isdigit() else a.lower())  count_nos = re.findall(r'\d+',' '.join(s_lst)) str_index = len(count_nos) no_index = 0 result=[] for i in range(0,len(splitted)):     if splitted[i].isdigit():         result.append(s_lst[no_index])         no_index+=1     else:         result.append(s_lst[str_index])         str_index+=1 print ' '.join(result) 

Answers 4

You could do in one sort provided you write a custom function for comparision. The idea is to sort the words in ascending order and integer in descending order in the same list . Incase of word and integer is compared then treat the word as smaller compared to word.

And then for printing the final result increment the index for word if a word is found , decrement the index for integer if digit is found.

The below code works in python2:

a = "12 I have car 8 200 a"  def custom_compare(x,y):     if x.isdigit() and y.isdigit():         return int(y) - int(x) #do a descending order     if x.isdigit() and y.isdigit() == False:         return 1     if x.isdigit() == False and y.isdigit():         return -1     if x.isdigit() == False and y.isdigit() == False:         # do ascending order         if x.lower() == y.lower():             return 0         elif x.lower() < y.lower():             return -1         else:             return 1  original_list = a.split(" ") sorted_list = sorted(original_list, cmp=custom_compare)  result = [] integer_index = -1 string_index = 0 for word in original_list:     if word.isdigit():         result.append(sorted_list[integer_index])         integer_index = integer_index - 1     else:         result.append(sorted_list[string_index])         string_index = string_index + 1  result ['8', 'a', 'car', 'have', '12', '200', 'I'] 

Python 3: import functools

a = "12 I have car 8 200 a"  def custom_compare(x,y):     if x.isdigit() and y.isdigit():         return int(y) - int(x) #do a descending order     if x.isdigit() and y.isdigit() == False:         return 1     if x.isdigit() == False and y.isdigit():         return -1     if x.isdigit() == False and y.isdigit() == False:         # do ascending order         if x.lower() == y.lower():             return 0         elif x.lower() < y.lower():             return -1         else:             return 1  original_list = a.split(" ") sorted_list = sorted(original_list, key=functools.cmp_to_key(custom_compare))  result = [] integer_index = -1 string_index = 0 for word in original_list:     if word.isdigit():         result.append(sorted_list[integer_index])         integer_index = integer_index - 1     else:         result.append(sorted_list[string_index])         string_index = string_index + 1  result 

PS:The word comparison could be efficiently written. I am from C background and I am not sure of the pythonic way of comparison.

Answers 5

s = "2 is a A -3 car 11 I 0 a"  def magick(s):   s = s.split()    def reverse(tuples):     return [(a, b) for (b, a) in tuples]    def do_sort(tuples):     firsts  = [a for a, _ in tuples]     seconds = [a for _, a in tuples]     return list(zip(sorted(firsts), seconds))    def str_is_int(x):     try:       int(x)       return True     except:       return False    indexed = list(enumerate(s))    ints = do_sort([(int(x), ix) for (ix, x) in indexed if     str_is_int(x)])   strs = do_sort([(    x , ix) for (ix, x) in indexed if not str_is_int(x)])    return ' '.join([str(b) for _, b in sorted(reverse(ints+strs))])  print(magick(s)) 

Answers 6

This solution utilizes a single custom sorting algorithm, after grouping the original input into integers and strings:

def gt(a, b):   return a > b if isinstance(a, int) and isinstance(b, int) else a[0].lower() > b[0].lower()  def type_sort(d):    '''similar to bubble sort, but does not swap elements of different types.        For instance, type_sort([5, 3, 'b', 'a']) => [3, 5, 'a', 'b']    '''    for _ in d:      for i in range(len(d)-1):        _c = d[i]        _t = d[i+1]        if isinstance(_c, type(_t)):          if gt(_c, _t):            d[i+1] = _c            d[i] = _t    return d  def get_type(x):   return int(x) if x.isdigit() else x  def sort_in_place(s:str):   _s = list(map(get_type, s.split()))   new_s = type_sort([i for i in _s if isinstance(i, int)]+[i for i in _s if isinstance(i, str)])   ints = iter(i for i in new_s if isinstance(i, int))   strings = iter(i for i in new_s if isinstance(i, str))   return ' '.join(map(str, [next(ints) if isinstance(i, int) else next(strings) for i in _s]))  print(sort_in_place(a)) 

Output:

'8 a car have 12 200 I' 
Read More

Tuesday, April 24, 2018

Does the performance of numpy differ depending on the operating system?

Leave a Comment

Reading the interesting book "From Python to Numpy" I met an example, the description of which is as follows:

Let's consider a simple example where we want to clear all the values from an array which has the dtype np.float32. How does one write it to maximize speed?

The provided results surprised me, and when I rechecked them I got a completely different behavior. So, I asked the author to double-check, but he received the same results as before (OS X 10) in the table below:

The variants were timed on three different computers: mine (Win10, Win7) and author's (OSX 10.13.3). With Python 3.6.4 and numpy 1.14.2, where each variant was timed for fixed 100 loops, best of 3.

Edit: This question is not about the fact that on different computers, with different characteristics, I get different times - this is obvious :) The question is that the behavior is very different on the two operating systems - which is not so obvious? (if it is of course so, I would be glad if someone could double-check).

The setup was: Z = np.ones(4*1000000, np.float32)

| Variant                     | Windows 10 | Ubuntu 17.10 | Windows 7 | OSX 10.13.3 | |                             |       computer 1          |   comp 2  |    comp 3   | | --------------------------- | ------------------------- | --------- | ----------- | | Z.view(np.float64)[...] = 0 | 758 usec   | 1.03 msec    | 2.72 msec | 1.01 msec   | | Z.view(np.float32)[...] = 0 | 757 usec   | 1.01 msec    | 2.61 msec | 1.58 msec   | | Z.view(np.float16)[...] = 0 | 760 usec   | 1.01 msec    | 2.62 msec | 2.85 msec   | | Z.view(np.complex)[...] = 0 | 1.06 msec  | 1.02 msec    | 3.26 msec | 918 usec    | | Z.view(np.int64)[...] = 0   | 758 usec   | 1.03 msec    | 2.69 msec | 1 msec      | | Z.view(np.int32)[...] = 0   | 757 usec   | 1.01 msec    | 2.62 msec | 1.46 msec   | | Z.view(np.int16)[...] = 0   | 760 usec   | 1.01 msec    | 2.63 msec | 2.87 msec   | | Z.view(np.int8)[...] = 0    | 758 usec   | 773 usec     | 2.68 msec | 614 usec    | | Z.fill(0)                   | 747 usec   | 998 usec     | 2.55 msec | N/A         | | Z[...] = 0                  | 750 usec   | 1 msec       | 2.59 msec | N/A         | 

As you can see from this table, on Windows the results doesn't depend on the viewed type, but on OS X this hack highly affects the performance. Can you provide the insight why this happens?

Edit: As I wrote above three computers are different.

The specs of the first computer: Windows 10 and Ubuntu 17.10
CPU: Intel Xenon E5-1650v4 3.60GHz
RAM: 128GB DDR4-2400

The specs of the second computer: Windows 7
CPU: Intel Pentium P6100 2.00GHz
RAM: 4GB DDR3-1333

The specs of the third computer: I don't have this information :)

Link to the issue

Edit 2: Add results for the first computer on Ubuntu 17.10.

1 Answers

Answers 1

Keep in mind that Python is a very high-level programming language, Pandas being also a high-level framework.

What you're essentially given to work with is a high level API for many operations that you can perform with the language, without the need to worry about the underlying implementation.

If you were to work with a lower-level API, to assign an array to a variable you'd have to allocate some memory, create a structure to hold your data, link it together (probably using pointers to memory addresses). And you didn't even touch the actual chip, there's still virtual memory mapping being done between your API and the actual data being saved to the chip. And that complexity is applied to basically everything you're doing with Python & Pandas.

Yet, you only have to do arr = [1, 2, 3], and not worry about it.

Now Python is expected to work the same on every platform you run it - at least in most of the cases.

Now, after the boring introduction is behind us - the whole idea of "expose uniform API, don't worry about implementation" is widely spread in computer programming. There are some subtle implementation details that differ one operating system from another, which may or may not impact performance of your software. I don't expect that to be significant, but it's still there and worth mentioning.

For example, there's an old answer about np.dot function performance differing between Linux and Windows. The author has way more knowledge than me on this subject, and points out that that particular function is a wrapper around CBLAS routines, which will use fastest routines available on given platform.

That being said - pandas is a very complex library which aims to make data analysis as simple as possible, through exposing simple-to-use API to the programmer. I expect that there are a lot more places where Pandas does a great job using the best mechanisms available on your platform to perform its tasks as fast as it can.

Read More

Wednesday, April 18, 2018

Horrible performance when upgrading from node v6.7.0 to v8.11.1

Leave a Comment

I have been spending the past few days investigating poor performance for an websocket graphql api application when upgrading node from v6.x to v8.x.

I have taken lots of flame graphs but I cannot figure out where the bottleneck is. Does anyone know what ___kdebug_trace_string (in c++) is? It appears to be taking significantly more time in my application after the upgrade.

Check out this flame graph:

Flame graph

Also check out these profile logs:

node v8.x profile log (slow): https://pastebin.com/2W65BZC8

node v6.x profile log: https://pastebin.com/BL4kM7B7

Thanks ahead!

1 Answers

Answers 1

kdebug_trace_string is a syscall that has been added to XNU in october 2015 for iOS 9 and OS X 10.11.

It's part of kdebug, the main XNU built-in debugging facility. When reading kdebug_trace.c, I found the following note in the comments :

Note that the userspace API is chosing to optimize fastpath, non-error performance by eliding validation of each debugid. This means that error cases which could have been caught in userspace will make a syscall before returning with the correct error code. This tradeoff in performance is intentional.

It explains why ___kdebug_trace_string is taking so much place on your flame graph.


This is just a guess and all of this is wrong if you're not using an Apple computer, but then, if it's wrong, I really want to know what's causing this mess.



Assuming I'm right, if kdebug_trace_string is called, so it means that node runs some kind of debugging utility. I downloaded node-v8.11.1-darwin-x64, and found the following line in node/config.gypi :

 'node_use_dtrace': 'true', 

So node v8.11.1 uses dtrace.
Then, looking at this line in osx/src/dtrace/libdtrace/dt_open.c, we can assume that dtrace uses kdebug_trace_string

So to fix this, one would want to prevent node from using dtrace. According to this answer, " When Node starts up, the .gypi is loaded like any other settings file.". So maybe you should juste set node_use_dtrace to false

BUT

I don't understand why you didn't face the same problem with node v6.7.0 :

  • In node-v6.7.0-darwin-x64, node_use_dtrace is set to true too
  • Node v6.7 approx. release date : 2016-09-28
  • OS X 10.11 approx release date : 2015-09-06

Could you tell me the value of node_use_dtrace for your two versions of node ?

Hope it helps, and hope I'm right,
Best regards

Read More

Friday, March 9, 2018

Hive Query Efficiency

Leave a Comment

Could you help me with a Hive Query Efficiency problem? I have two queries working for the same problem. I just cannot figure out why one is much faster than the other. If you know please feel free to provide insight. Any info is welcomed!

Problem: I am trying to check the minimum value of a bunch of variables in a Hive parquet table.

Queries: I tried two two queries as follows:

query 1

drop table if exists tb_1 purge; create table if not exists tb_1 as select 'v1' as name, min(v1) as min_value from src_tb union all select 'v2' as name, min(v2) as min_value from src_tb union all select 'v3' as name, min(v3) as min_value from src_tb union all ... select 'v200' as name, min(v200) as min_value from src_tb ; 

query 2

drop table if exists tb_2 purge; create table if not exists tb_2 as select min(v1) as min_v1 , min(v2) as min_v2 , min(v3) as min_v3 ... , min(v200) as min_v200 from src_tb ; 

Result: Query 2 is much faster than query 1. It took probably 5 mins to finish the second query. I don't know how long will query 1 take. But after I submit the first query, it took a long time to even react to the query, by which I mean that usually after I submit a query, the system will start to analyze and provides some compiling information in the terminal. However, for my first query, after my submission, the system won't even react to this. So I just killed it.

What do you think? Thank you in advance.

3 Answers

Answers 1

Query execution time depends on environment that you execute it.

In MSSQL.

Some people like you think query execution is similar to algorithm that they see in some theoretical resources, but in practical situation, it depends on other things.

For example both of your queries have SELECT statement that perform on a table and at first glance, they need to read all rows, but database server must analyze the statement to determine the most efficient way to extract the requested data. This is referred to as optimizing the SELECT statement. The component that does this is called the Query Optimizer. The input to the Query Optimizer consists of the query, the database schema (table and index definitions), and the database statistics. The output of the Query Optimizer is a query execution plan, sometimes referred to as a query plan or just a plan. (Please see this for more information about query-processing architecture)

You can see execution plan in MSSQL by reading this article and I think you will understand better by seeing execution plan for both of your queries.

Edit (Hive)

Hive provides an EXPLAIN command that shows the execution plan for a query. The syntax for this statement is as follows:

EXPLAIN [EXTENDED|DEPENDENCY|AUTHORIZATION] query 

A Hive query gets converted into a sequence of stages. The description of the stages itself shows a sequence of operators with the metadata associated with the operators.

Please see LanguageManual Explain for more information.

Answers 2

What is surprising? The first query has to read src_tb a total of 200 times. The second reads the data once and performs 200 aggregations. It is a no brainer that it is faster.

Answers 3

As mentioned, source table is in parquet. Hive leverages columnar approach, but the latency caused while executing your query1 is due to scheduling delay.

Here's the breakdown.

Query 1 :

Since It is a Union All operation of 200 queries, when you run EXPLAIN on your query1, you should probably see roughly 202-205 stages in the execution plan.However resource manager will keep you waiting until it finds resources to schedule roughly about 200+ stages, in some cases application master may schedule/run multiple stages at once.Even though application master tries to run multiple stages in parallel, the scheduling delay is relatively higher compared to query2. This was the reason why you didn't see any response on your hive client when you submitted query 1. Coming columnar approach, In query1 it is definitely an optimization since you are selecting a single column and your source table is in parquet, but the scheduling delay out weighs in you case.

Query 2:

As opposed to query 1, when you run EXPLAIN on the query2 you may see 3 stages, if not fewer than 5 stages.However there is no scheduling delay in this case.This is the reason why you are seeing the results quick.Moving on to columnar format, in case you are selecting most of the columns in your source table, column/row orientation may not make any difference. Otherwise it is optimal as opposed to row oriented.

Read More

Monday, February 19, 2018

Javascript performance optimization

Leave a Comment

I created the following js function

function csvDecode(csvRecordsList) {     var cel;     var chk;     var chkACB;     var chkAF;     var chkAMR;     var chkAN;     var csvField;     var csvFieldLen;     var csvFieldsList;     var csvRow;     var csvRowLen = csvRecordsList.length;     var frag = document.createDocumentFragment();     var injectFragInTbody = function () {tblbody.replaceChild(frag, tblbody.firstElementChild);};     var isFirstRec;     var len;     var newEmbtyRow;     var objCells;     var parReEx = new RegExp(myCsvParag, 'ig');     var tblbody;     var tblCount = 0;     var tgtTblBodyID;      for (csvRow = 0; csvRow < csvRowLen; csvRow++)     {         if (csvRecordsList[csvRow].startsWith(myTBodySep))         {             if (frag.childElementCount > 0)             {                 injectFragInTbody();             }             tgtTblBodyID = csvRecordsList[csvRow].split(myTBodySep)[1];             newEmbtyRow = getNewEmptyRow(tgtTblBodyID);             objCells = newEmbtyRow.cells;             len = newEmbtyRow.querySelectorAll('input')[0].parentNode.cellIndex; // Finds the cell index where is placed the first input (Check-box or button)              tblbody = getElById(tgtTblBodyID);             chkAF = toBool(tblbody.dataset.acceptfiles);             chkACB = toBool(tblbody.dataset.acceptcheckboxes) ;             chkAN = toBool(tblbody.dataset.acceptmultiplerows) ;             tblCount++;             continue;         }          csvRecordsList[csvRow] = csvRecordsList[csvRow].replace(parReEx, myInnerHTMLParag); // Replaces all the paragraph symbols ¶ used into the db.csv file with the tag <br> needed into the HTML content of table cells, this way will be possible to use line breaks into table cells         csvFieldsList = csvRecordsList[csvRow].split(myEndOfFld);          csvFieldLen = csvFieldsList.length;         for (csvField = 0; csvField < csvFieldLen; csvField++)         {             cel = chkAN ? csvField + 1 : csvField;             if (chkAF && cel === 1) {objCells[cel].innerHTML =  makeFileLink(csvFieldsList[csvField]);}              else if (chkACB && cel === len) {objCells[cel].firstChild.checked = toBool(csvFieldsList[csvField]);}             else {objCells[cel].innerHTML = csvFieldsList[csvField];}         }         frag.appendChild(newEmbtyRow.cloneNode(true));     }     injectFragInTbody();      var recNum = getElById(tgtTblBodyID).childElementCount;     customizeHtmlTitle();     return csvRow - tblCount + ' (di cui '+ recNum + ' record di documenti)'; } 

More than 90% of records could contain file names that have to be processed by the following makeFileLink function:

function makeFileLink(fname) {     return ['<a href="', dirDocSan, fname, '" target="', previewWinName, '" title="Apri il file allegato: ', fname, '" >', fname, '</a>'].join(''); } 

It aims to decode a record list from a special type of *.db.csv file (= a comma-separated values where commas are replaced by another symbol I hard-coded into the var myEndOfFld). (This special type of *.db.csv is created by another function I wrote and it is just a "text" file).

The record list to decode and append to HTML tables is passed to the function with its lone parameter: (csvRecordsList).

Into the csv file is hosted data coming from more HTML tables.

Tables are different for number of rows and columns and for some other contained data type (which could be filenames, numbers, string, dates, checkbox values).

Some tables could be just 1 row, others accept more rows.

A row of data has the following basic structure:

data field content 1|data field content 2|data field content 3|etc... 

Once decoded by my algorithm it will be rendered correctly into the HTML td element even if into a field there are more paragraphs. In fact the tag
will be added where is needed by the code:

csvRecordsList[csvRow].replace(par, myInnerHTMLParag) 

that replaces all the char I choose to represent the paragraph symbol I have hard-coded into the variable myCsvParag.

Isn't possible to know at programming time the number of records to load in each table nor the number of records loaded from the CSV file, nor the number of fields of each record or what table field is going to contain data or will be empty: in the same record some fields could contain data others could be empty. Everything has to be discovered at runtime.

Into the special csv file each table is separated from the next by a row witch contains just a string with the following pattern: myTBodySep = tablebodyid where myTBodySep = "targettbodydatatable" that is just a hard coded string of my choice. tablebodyid is just a placeholder that contains a string representing the id of the target table tbody element to insert new record in, for example: tBodyDataCars, tBodyDataAnimals... etc.

So when the first for loop finds into the csvRecordsList a string staring with the string into the variable myTBodySep it gets the tablebodyid from the same row: this will be the new tbodyid that has to be targeted for injecting next records in it

Each table is archived into the CSV file

The first for loop scan the csv record list from the file and the second for loop prepare what is needed to compile the targeted table with data.

The above code works well but it is a little bit slow: in fact to load into the HTML tables about 300 records from the CSV file it takes a bit more of 2.5 seconds on a computer with 2 GB ram and Pentium core 2 4300 dual-core at 1800 MHz but if I comment the row that update the DOM the function needs less than 0.1 sec. So IMHO the bottle neck is the fragment and DOM manipulating part of the code.

My aim and hope is to optimize the speed of the above code without losing functionalities.

Notice that I'm targeting just modern browsers and I don't care about others and non standards-compliant browsers... I feel sorry for them...

Any suggestions? Thanks in advance.

Edit 16-02.2018

I don't know if it is useful but lastly I've noticed that if data is loaded from browser sessionstorage the load and rendering time is more or less halved. But strangely it is the exact same function that loads data from both file and sessionstorage. I don't understand why of this different behavior considering that the data is exactly the same and in both cases is passed to a variable handled by the function itself before starting checking performance timing.

Edit 18.02.2018

  1. Number of rows is variable depending on the target table: from 1 to 1000 (could be even more in particular cases)
  2. Number of columns depending on the target table: from 10 to 18-20

3 Answers

Answers 1

In fact, DOM manipulations are way slower than simple innerHTML update.

I've made a simple benchmark for you.

Lets make a table 300x300 and fill 90000 cells with 'A'. There are two functions.

The first one is a simplified variant of your code which uses DOM methods:

var table = document.querySelector('table tbody');  var cells_in_row = 300, rows_total = 300;    var start = performance.now();  fill_table_1();  console.log('using DOM methods: ' + (performance.now() - start).toFixed(2) + 'ms');    table.innerHTML = '<tbody></tbody>';      function fill_table_1() {    var frag = document.createDocumentFragment();      var injectFragInTbody = function() {      table.replaceChild(frag, table.firstElementChild)    }      var getNewEmptyRow = function() {      var row = table.firstElementChild;      if (!row) {        row = table.insertRow(0);        for (var c = 0; c < cells_in_row; c++) row.insertCell(c);      }      return row.cloneNode(true);    }      for (var r = 0; r < rows_total; r++) {      var new_row = getNewEmptyRow();      var cells = new_row.cells;      for (var c = 0; c < cells_in_row; c++) cells[c].innerHTML = 'A';      frag.appendChild(new_row.cloneNode(true));    }    injectFragInTbody();    return false;  }
<table><tbody></tbody></table>

The second one prepares html string and put it into the table's innerHTML:

var table = document.querySelector('table tbody');  var cells_in_row = 300, rows_total = 300;    var start = performance.now();  fill_table_2();  console.log('setting innerHTML: ' + (performance.now() - start).toFixed(2) + 'ms');    table.innerHTML = '<tbody></tbody>';    function fill_table_2() {// setting innerHTML    var html = '';    for (var r = 0; r < rows_total; r++) {      html += '<tr>';      for (var c = 0; c < cells_in_row; c++) html += '<td>A</td>';      html += '</tr>';    }    table.innerHTML = html;    return false;  }
<table><tbody></tbody></table>

I believe you'll come to some conclusions.

Answers 2

I've got two thoughts for you.

1: If you want to know which parts of your code are (relatively) slow you can do very simple performance testing using the technique described here. I didn't read all of the code sample you gave but you can add those performance tests yourself and check out which operations take more time.

2: What I know of JavaScript and the browser is that changing the DOM is an expensive operation, you don't want to change the DOM too many times. What you can do instead is build up a set of changes and then apply all those changes with one DOM change. This may make your code less nice, but that's often the tradeoff you have when you want to have high performance.

Let me know how this works out for you.

Answers 3

You should start by refactoring your code in multiples functions to make it a bit more readable. Make sure that you are separating DOM manipulation functions from data processing functions. Ideally, create a class and get those variables out of your function, this way you can access them with this.

Then, you should execute each function processing data in a web worker, so you're sure that your UI won't get blocked by the process. You won't be able to access this in a web worker so you will have to limit it to pure "input/output" operations.

Good luck!

Read More

Thursday, January 18, 2018

Faster sqlite 3 query in go? I need to process 1million+ rows as fast as possible

Leave a Comment

What's the fastest way to read a sqlite3 table in golang?

package main  import (     "fmt"     "database/sql"     _ "github.com/mattn/go-sqlite3"     "log"     "time" )  func main() {     start := time.Now()      db, err := sql.Open("sqlite3", "/Users/robertking/go/src/bitbucket.org/thematicanalysis/optimization_test/robs.db")     if err != nil {         log.Fatal(err)     }     defer db.Close()     rows, err := db.Query("select * from data")     if err != nil {         log.Fatal(err)     }     defer rows.Close()      for rows.Next() {     }     err = rows.Err()     if err != nil {         log.Fatal(err)     }     fmt.Println(time.Since(start)) } 

This takes 8 seconds in Go because .Next is slow. In python a fetchall takes only 4 seconds! I'm rewriting in GO to gain performance not lose performance.

Here is the python code, I couldn't find an equivalent of fetchall in go:

import time  start = time.time() import sqlite3 conn = sqlite3.connect('/Users/robertking/go/src/bitbucket.org/thematicanalysis/optimization_test/robs.db') c = conn.cursor() c.execute("SELECT * FROM data") x = c.fetchall() print time.time() - start 

Edit: adding bounty. I'm reading the data in go, python and C, here are results. Dont want to use C, but will stick with python if GO isnt faster.:

py: 2.45s go: 2.13s (using github.com/mxk/go-sqlite/sqlite3 instead of github.com/mattn/go-sqlite3) c:  0.32s 

I feel like go should be closer to the c side of thing? anyone know how to make it faster? is it possible to avoid mutex with readonly mode?

edit:

It seems like all the sqlite3 implementations are slow (too much reflection and too many cgo calls for conversions). So i'll have to just write my own interface.

Here's the schema:

CREATE TABLE mytable (   c0   REAL,   c1   INTEGER,   c15  TEXT,   c16  TEXT,   c17  TEXT,   c18  TEXT,   c19  TEXT,   c47  TEXT,   c74  REAL DEFAULT 0,   c77  TEXT,   c101 TEXT,   c103 TEXT,   c108 TEXT,   c110 TEXT,   c125 TEXT,   c126 TEXT,   c127 REAL DEFAULT 0,   x    INTEGER     PRIMARY KEY ); 

and the query is dynamic but usually something like this:

SELECT c77,c77,c125,c126,c127,c74 from mytable 

edit:

looks like i'll fork the sqlite3 implementation and make some methods that focus on performance,

this is an example of some code which is much faster:.

package main   /*  #cgo LDFLAGS: -l sqlite3  #include "sqlite3.h" */ import "C"  import (     //"database/sql"     "log"     "reflect"     "unsafe" )  type Row struct {     v77 string     v125 string     v126 string     v127 float64     v74 float64 }  // cStr returns a pointer to the first byte in s. func cStr(s string) *C.char {     h := (*reflect.StringHeader)(unsafe.Pointer(&s))     return (*C.char)(unsafe.Pointer(h.Data)) }  func main() {     getDataFromSqlite() }  func getDataFromSqlite() {     var db *C.sqlite3     name := "../data_dbs/all_columns.db"     rc := C.sqlite3_open_v2(cStr(name+"\x00"), &db, C.SQLITE_OPEN_READONLY, nil)    var stmt *C.sqlite3_stmt;   rc = C.sqlite3_prepare_v2(db, cStr("SELECT c77,c125,c126,c127,c74 from data\x00"), C.int(-1), &stmt, nil);   rc = C.sqlite3_reset(stmt);      var result C.double     result = 0.0     rc = C.sqlite3_step(stmt)     for rc == C.SQLITE_ROW {     C.GoString((*C.char)(unsafe.Pointer(C.sqlite3_column_text(stmt, 0))))     C.GoString((*C.char)(unsafe.Pointer(C.sqlite3_column_text(stmt, 1))))     C.GoString((*C.char)(unsafe.Pointer(C.sqlite3_column_text(stmt, 2))))     C.sqlite3_column_double(stmt, 3)     result += C.sqlite3_column_double(stmt, 4)         rc = C.sqlite3_step(stmt)   }     log.Println(result) } 

2 Answers

Answers 1

Introduction

My assumption was that we have a problem with how the performance is measured here, so I wrote a little Go program to generate records and save them into a SQLite database as well as a Python and Go implementation of a little task to do on those records.

You can find the according repository at https://github.com/mwmahlberg/sqlite3perf

The data model

The records generated consist of

The table's schema is relatively simple:

sqlite> .schema CREATE TABLE bench (ID int PRIMARY KEY ASC, rand TEXT, hash TEXT); 

First I generated 1.5M records and vacuumed the sqlite database afterwards with

$ ./sqlite3perf generate -r 1500000 -v 

Next I called the Go implementation against those 1.5M records. Both the Go as well as the Python implementation basically do the same simple task:

  1. Read all entries from the database.
  2. For each row, decode the random value from hex, then create a SHA256 hex from the result.
  3. Compare the generated SHA256 hex string against the one stored in the database
  4. If they match, continue, otherwise break.

Assumptions

My assumption explicitly was that Python did some type of lazy loading and/or possibly even execution of the SQL query.

The results

Go implementation

$ ./sqlite3perf bench 2017/12/31 15:21:48 bench called 2017/12/31 15:21:48 Time after query: 4.824009ms 2017/12/31 15:21:48 Beginning loop 2017/12/31 15:21:48 Acessing the first result set      ID 0,     rand: 6a8a4ad02e5e872a,     hash: 571f1053a7c2aaa56e5c076e69389deb4db46cc08f5518c66a4bc593e62b9aa4 took 548.32µs 2017/12/31 15:21:50 641,664 rows processed 2017/12/31 15:21:52 1,325,186 rows processed 2017/12/31 15:21:53 1,500,000 rows processed 2017/12/31 15:21:53 Finished loop after 4.519083493s 2017/12/31 15:21:53 Average 3.015µs per record, 4.523936078s overall 

Note the values for "time after query" ( the time the query command took to return) and the time it took to access the first result set after the iteration over the result set was started.

Python implementation

$ python bench.py  12/31/2017 15:25:41 Starting up 12/31/2017 15:25:41 Time after query: 1874µs 12/31/2017 15:25:41 Beginning loop 12/31/2017 15:25:44 Accessing first result set     ID: 0     rand: 6a8a4ad02e5e872a     hash: 571f1053a7c2aaa56e5c076e69389deb4db46cc08f5518c66a4bc593e62b9aa4 took 2.719312 s 12/31/2017 15:25:50 Finished loop after 9.147431s 12/31/2017 15:25:50 Average: 6.098µs per record, 0:00:09.149522 overall 

Again, note the value for "time after query" and the time it took to access the first result set.

Summary

It took the Go implementation quite a while to return after the SELECT query was send, while Python seemed to be blazing fast in comparison. However, from the time it took to actually access the first result set, we can see that the Go implementation is more than 500 times faster to actually access the first result set (5.372329ms vs 2719.312ms) and about double as fast for the task at hand as the Python implementation.

Notes

  • In order to prove the assumption that Python actually does lazy loading on the result set, each and every row and column had to be accessed in order to make sure that Python is forced to actually read the value from the database.
  • I chose a hashing task because presumably the implementation of SHA256 is highly optimised in both languages.

Conclusion

Python does seem to do lazy loading of result sets and possibly does not even execute a query unless the according result set is actually accessed. In this simulated scenario, mattn's SQLite driver for Go outperforms Python's by between roughly 100% and orders of magnitude, depending on what you want to do.

Edit: So in order to have a fast processing, implement your task in Go. While it takes longer to send the actual query, accessing the individual rows of the result set is by far faster. I'd suggest starting out with a small subset of your data, say 50k records. Then, to further improve your code, use profiling to identify your bottlenecks. Depending on what you want to do during processing, pipelines for example might help, but how to improve the processing speed of the task at hand is difficult to say without actual code or a thorough description.

Answers 2

Scanning Values from the retrieved rows example read step 10.
Since Query() & QueryRow() returns a pointer to Rows and pointer to Row from the database query respectively, we can use the Scan() functions on Rows and Row struct to get access to the values in the rows struct.

for rows.Next() {   var empID sql.NullInt64  var empName sql.NullString  var empAge sql.NullInt64  var empPersonId sql.NullInt64   if err := rows.Scan(&empID, &empName, &empAge,                             &empPersonId); err != nil {           log.Fatal(err)  }   fmt.Printf("ID %d with personID:%d & name %s is age %d\n",                           empID.Int64, empPersonId.Int64, empName.String, empAge.Int64) } 

We also used the Scan() function from Row struct. Scan() is the only method declared in the Row Struct.

func (r *Row) Scan(dest ...interface{}) error 
Read More

Thursday, December 28, 2017

Why are numpy functions so slow on pandas series / dataframes?

Leave a Comment

Consider a small MWE, taken from another question:

DateTime                Data 2017-11-21 18:54:31     1 2017-11-22 02:26:48     2 2017-11-22 10:19:44     3 2017-11-22 15:11:28     6 2017-11-22 23:21:58     7 2017-11-28 14:28:28    28 2017-11-28 14:36:40     0 2017-11-28 14:59:48     1 

The goal is to clip all values with an upper bound of 1. My answer uses np.clip, which works fine.

np.clip(df.Data, a_min=None, a_max=1) array([1, 1, 1, 1, 1, 1, 0, 1]) 

Or,

np.clip(df.Data.values, a_min=None, a_max=1) array([1, 1, 1, 1, 1, 1, 0, 1]) 

Both of which return the same answer. My question is about the relative performance of these two methods. Consider -

df = pd.concat([df]*1000).reset_index(drop=True)  %timeit np.clip(df.Data, a_min=None, a_max=1) 1000 loops, best of 3: 270 µs per loop  %timeit np.clip(df.Data.values, a_min=None, a_max=1) 10000 loops, best of 3: 23.4 µs per loop 

Why is there such a massive difference between the two, just by calling values on the latter? In other words...

Why are numpy functions so slow on pandas objects?

4 Answers

Answers 1

Yes, it seems like np.clip is a lot slower on pandas.Series than on numpy.ndarrays. That's correct but it's actually (at least asymptomatically) not that bad. 8000 elements is still in the regime where constant factors are major contributors in the runtime. I think this is a very important aspect to the question, so I'm visualizing this (borrowing from another answer):

# Setup  import pandas as pd import numpy as np  def on_series(s):     return np.clip(s, a_min=None, a_max=1)  def on_values_of_series(s):     return np.clip(s.values, a_min=None, a_max=1)  # Timing setup timings = {on_series: [], on_values_of_series: []} sizes = [2**i for i in range(1, 26, 2)]  # Timing for size in sizes:     func_input = pd.Series(np.random.randint(0, 30, size=size))     for func in timings:         res = %timeit -o func(func_input)         timings[func].append(res)  %matplotlib notebook  import matplotlib.pyplot as plt import numpy as np  fig, (ax1, ax2) = plt.subplots(1, 2)  for func in timings:     ax1.plot(sizes,               [time.best for time in timings[func]],               label=str(func.__name__)) ax1.set_xscale('log') ax1.set_yscale('log') ax1.set_xlabel('size') ax1.set_ylabel('time [seconds]') ax1.grid(which='both') ax1.legend()  baseline = on_values_of_series # choose one function as baseline for func in timings:     ax2.plot(sizes,               [time.best / ref.best for time, ref in zip(timings[func], timings[baseline])],               label=str(func.__name__)) ax2.set_yscale('log') ax2.set_xscale('log') ax2.set_xlabel('size') ax2.set_ylabel('time relative to {}'.format(baseline.__name__)) ax2.grid(which='both') ax2.legend()  plt.tight_layout() 

enter image description here

It's a log-log plot because I think this shows the important features more clearly. For example it shows that np.clip on a numpy.ndarray is faster but it also has a much smaller constant factor in that case. The difference for large arrays is only ~3! That's still a big difference but way less than the difference on small arrays.

However, that's still not an answer to the question where the time difference comes from.

The solution is actually quite simple: np.clip delegates to the clip method of the first argument:

>>> np.clip?? Source:    def clip(a, a_min, a_max, out=None):     """     ...     """     return _wrapfunc(a, 'clip', a_min, a_max, out=out)  >>> np.core.fromnumeric._wrapfunc?? Source:    def _wrapfunc(obj, method, *args, **kwds):     try:         return getattr(obj, method)(*args, **kwds)     # ...     except (AttributeError, TypeError):         return _wrapit(obj, method, *args, **kwds) 

The getattr line of the _wrapfunc function is the important line here, because np.ndarray.clip and pd.Series.clip are different methods, yes, completely different methods:

>>> np.ndarray.clip <method 'clip' of 'numpy.ndarray' objects> >>> pd.Series.clip <function pandas.core.generic.NDFrame.clip> 

Unfortunately is np.ndarray.clip a C-function so it's hard to profile it, however pd.Series.clip is a regular Python function so it's easy to profile. Let's use a Series of 5000 integers here:

s = pd.Series(np.random.randint(0, 100, 5000)) 

For the np.clip on the values I get the following line-profiling:

%load_ext line_profiler %lprun -f np.clip -f np.core.fromnumeric._wrapfunc np.clip(s.values, a_min=None, a_max=1)  Timer unit: 4.10256e-07 s  Total time: 2.25641e-05 s File: numpy\core\fromnumeric.py Function: clip at line 1673  Line #      Hits         Time  Per Hit   % Time  Line Contents ==============================================================   1673                                           def clip(a, a_min, a_max, out=None):   1674                                               """   ...   1726                                               """   1727         1           55     55.0    100.0      return _wrapfunc(a, 'clip', a_min, a_max, out=out)  Total time: 1.51795e-05 s File: numpy\core\fromnumeric.py Function: _wrapfunc at line 55  Line #      Hits         Time  Per Hit   % Time  Line Contents ==============================================================     55                                           def _wrapfunc(obj, method, *args, **kwds):     56         1            2      2.0      5.4      try:     57         1           35     35.0     94.6          return getattr(obj, method)(*args, **kwds)     58                                                59                                               # An AttributeError occurs if the object does not have     60                                               # such a method in its class.     61                                                62                                               # A TypeError occurs if the object does have such a method     63                                               # in its class, but its signature is not identical to that     64                                               # of NumPy's. This situation has occurred in the case of     65                                               # a downstream library like 'pandas'.     66                                               except (AttributeError, TypeError):     67                                                   return _wrapit(obj, method, *args, **kwds) 

But for np.clip on the Series I get a totally different profiling result:

%lprun -f np.clip -f np.core.fromnumeric._wrapfunc -f pd.Series.clip -f pd.Series._clip_with_scalar np.clip(s, a_min=None, a_max=1)  Timer unit: 4.10256e-07 s  Total time: 0.000823794 s File: numpy\core\fromnumeric.py Function: clip at line 1673  Line #      Hits         Time  Per Hit   % Time  Line Contents ==============================================================   1673                                           def clip(a, a_min, a_max, out=None):   1674                                               """   ...   1726                                               """   1727         1         2008   2008.0    100.0      return _wrapfunc(a, 'clip', a_min, a_max, out=out)  Total time: 0.00081846 s File: numpy\core\fromnumeric.py Function: _wrapfunc at line 55  Line #      Hits         Time  Per Hit   % Time  Line Contents ==============================================================     55                                           def _wrapfunc(obj, method, *args, **kwds):     56         1            2      2.0      0.1      try:     57         1         1993   1993.0     99.9          return getattr(obj, method)(*args, **kwds)     58                                                59                                               # An AttributeError occurs if the object does not have     60                                               # such a method in its class.     61                                                62                                               # A TypeError occurs if the object does have such a method     63                                               # in its class, but its signature is not identical to that     64                                               # of NumPy's. This situation has occurred in the case of     65                                               # a downstream library like 'pandas'.     66                                               except (AttributeError, TypeError):     67                                                   return _wrapit(obj, method, *args, **kwds)  Total time: 0.000804922 s File: pandas\core\generic.py Function: clip at line 4969  Line #      Hits         Time  Per Hit   % Time  Line Contents ==============================================================   4969                                               def clip(self, lower=None, upper=None, axis=None, inplace=False,   4970                                                        *args, **kwargs):   4971                                                   """   ...   5021                                                   """   5022         1           12     12.0      0.6          if isinstance(self, ABCPanel):   5023                                                       raise NotImplementedError("clip is not supported yet for panels")   5024                                              5025         1           10     10.0      0.5          inplace = validate_bool_kwarg(inplace, 'inplace')   5026                                              5027         1           69     69.0      3.5          axis = nv.validate_clip_with_axis(axis, args, kwargs)   5028                                              5029                                                   # GH 17276   5030                                                   # numpy doesn't like NaN as a clip value   5031                                                   # so ignore   5032         1          158    158.0      8.1          if np.any(pd.isnull(lower)):   5033         1            3      3.0      0.2              lower = None   5034         1           26     26.0      1.3          if np.any(pd.isnull(upper)):   5035                                                       upper = None   5036                                              5037                                                   # GH 2747 (arguments were reversed)   5038         1            1      1.0      0.1          if lower is not None and upper is not None:   5039                                                       if is_scalar(lower) and is_scalar(upper):   5040                                                           lower, upper = min(lower, upper), max(lower, upper)   5041                                              5042                                                   # fast-path for scalars   5043         1            1      1.0      0.1          if ((lower is None or (is_scalar(lower) and is_number(lower))) and   5044         1           28     28.0      1.4                  (upper is None or (is_scalar(upper) and is_number(upper)))):   5045         1         1654   1654.0     84.3              return self._clip_with_scalar(lower, upper, inplace=inplace)   5046                                              5047                                                   result = self   5048                                                   if lower is not None:   5049                                                       result = result.clip_lower(lower, axis, inplace=inplace)   5050                                                   if upper is not None:   5051                                                       if inplace:   5052                                                           result = self   5053                                                       result = result.clip_upper(upper, axis, inplace=inplace)   5054                                              5055                                                   return result  Total time: 0.000662153 s File: pandas\core\generic.py Function: _clip_with_scalar at line 4920  Line #      Hits         Time  Per Hit   % Time  Line Contents ==============================================================   4920                                               def _clip_with_scalar(self, lower, upper, inplace=False):   4921         1            2      2.0      0.1          if ((lower is not None and np.any(isna(lower))) or   4922         1           25     25.0      1.5                  (upper is not None and np.any(isna(upper)))):   4923                                                       raise ValueError("Cannot use an NA value as a clip threshold")   4924                                              4925         1           22     22.0      1.4          result = self.values   4926         1          571    571.0     35.4          mask = isna(result)   4927                                              4928         1           95     95.0      5.9          with np.errstate(all='ignore'):   4929         1            1      1.0      0.1              if upper is not None:   4930         1          141    141.0      8.7                  result = np.where(result >= upper, upper, result)   4931         1           33     33.0      2.0              if lower is not None:   4932                                                           result = np.where(result <= lower, lower, result)   4933         1           73     73.0      4.5          if np.any(mask):   4934                                                       result[mask] = np.nan   4935                                              4936         1           90     90.0      5.6          axes_dict = self._construct_axes_dict()   4937         1          558    558.0     34.6          result = self._constructor(result, **axes_dict).__finalize__(self)   4938                                              4939         1            2      2.0      0.1          if inplace:   4940                                                       self._update_inplace(result)   4941                                                   else:   4942         1            1      1.0      0.1              return result 

I stopped going into the subroutines at that point because it already highlights where the pd.Series.clip does much more work than the np.ndarray.clip. Just compare the total time of the np.clip call on the values (55 timer units) to one of the first checks in the pandas.Series.clip method, the if np.any(pd.isnull(lower)) (158 timer units). At that point the pandas method didn't even start at clipping and it already takes 3 times longer.

However several of these "overheads" become insignificant when the array is big:

s = pd.Series(np.random.randint(0, 100, 1000000))  %lprun -f np.clip -f np.core.fromnumeric._wrapfunc -f pd.Series.clip -f pd.Series._clip_with_scalar np.clip(s, a_min=None, a_max=1)  Timer unit: 4.10256e-07 s  Total time: 0.00593476 s File: numpy\core\fromnumeric.py Function: clip at line 1673  Line #      Hits         Time  Per Hit   % Time  Line Contents ==============================================================   1673                                           def clip(a, a_min, a_max, out=None):   1674                                               """   ...   1726                                               """   1727         1        14466  14466.0    100.0      return _wrapfunc(a, 'clip', a_min, a_max, out=out)  Total time: 0.00592779 s File: numpy\core\fromnumeric.py Function: _wrapfunc at line 55  Line #      Hits         Time  Per Hit   % Time  Line Contents ==============================================================     55                                           def _wrapfunc(obj, method, *args, **kwds):     56         1            1      1.0      0.0      try:     57         1        14448  14448.0    100.0          return getattr(obj, method)(*args, **kwds)     58                                                59                                               # An AttributeError occurs if the object does not have     60                                               # such a method in its class.     61                                                62                                               # A TypeError occurs if the object does have such a method     63                                               # in its class, but its signature is not identical to that     64                                               # of NumPy's. This situation has occurred in the case of     65                                               # a downstream library like 'pandas'.     66                                               except (AttributeError, TypeError):     67                                                   return _wrapit(obj, method, *args, **kwds)  Total time: 0.00591302 s File: pandas\core\generic.py Function: clip at line 4969  Line #      Hits         Time  Per Hit   % Time  Line Contents ==============================================================   4969                                               def clip(self, lower=None, upper=None, axis=None, inplace=False,   4970                                                        *args, **kwargs):   4971                                                   """   ...   5021                                                   """   5022         1           17     17.0      0.1          if isinstance(self, ABCPanel):   5023                                                       raise NotImplementedError("clip is not supported yet for panels")   5024                                              5025         1           14     14.0      0.1          inplace = validate_bool_kwarg(inplace, 'inplace')   5026                                              5027         1           97     97.0      0.7          axis = nv.validate_clip_with_axis(axis, args, kwargs)   5028                                              5029                                                   # GH 17276   5030                                                   # numpy doesn't like NaN as a clip value   5031                                                   # so ignore   5032         1          125    125.0      0.9          if np.any(pd.isnull(lower)):   5033         1            2      2.0      0.0              lower = None   5034         1           30     30.0      0.2          if np.any(pd.isnull(upper)):   5035                                                       upper = None   5036                                              5037                                                   # GH 2747 (arguments were reversed)   5038         1            2      2.0      0.0          if lower is not None and upper is not None:   5039                                                       if is_scalar(lower) and is_scalar(upper):   5040                                                           lower, upper = min(lower, upper), max(lower, upper)   5041                                              5042                                                   # fast-path for scalars   5043         1            2      2.0      0.0          if ((lower is None or (is_scalar(lower) and is_number(lower))) and   5044         1           32     32.0      0.2                  (upper is None or (is_scalar(upper) and is_number(upper)))):   5045         1        14092  14092.0     97.8              return self._clip_with_scalar(lower, upper, inplace=inplace)   5046                                              5047                                                   result = self   5048                                                   if lower is not None:   5049                                                       result = result.clip_lower(lower, axis, inplace=inplace)   5050                                                   if upper is not None:   5051                                                       if inplace:   5052                                                           result = self   5053                                                       result = result.clip_upper(upper, axis, inplace=inplace)   5054                                              5055                                                   return result  Total time: 0.00575753 s File: pandas\core\generic.py Function: _clip_with_scalar at line 4920  Line #      Hits         Time  Per Hit   % Time  Line Contents ==============================================================   4920                                               def _clip_with_scalar(self, lower, upper, inplace=False):   4921         1            2      2.0      0.0          if ((lower is not None and np.any(isna(lower))) or   4922         1           28     28.0      0.2                  (upper is not None and np.any(isna(upper)))):   4923                                                       raise ValueError("Cannot use an NA value as a clip threshold")   4924                                              4925         1          120    120.0      0.9          result = self.values   4926         1         3525   3525.0     25.1          mask = isna(result)   4927                                              4928         1           86     86.0      0.6          with np.errstate(all='ignore'):   4929         1            2      2.0      0.0              if upper is not None:   4930         1         9314   9314.0     66.4                  result = np.where(result >= upper, upper, result)   4931         1           61     61.0      0.4              if lower is not None:   4932                                                           result = np.where(result <= lower, lower, result)   4933         1          283    283.0      2.0          if np.any(mask):   4934                                                       result[mask] = np.nan   4935                                              4936         1           78     78.0      0.6          axes_dict = self._construct_axes_dict()   4937         1          532    532.0      3.8          result = self._constructor(result, **axes_dict).__finalize__(self)   4938                                              4939         1            2      2.0      0.0          if inplace:   4940                                                       self._update_inplace(result)   4941                                                   else:   4942         1            1      1.0      0.0              return result 

There are still multiple function calls, for example isna and np.where, that take a significant amount of time, but overall this is at least comparable to the np.ndarray.clip time (that's in the regime where the timing difference is ~3 on my computer).

The takeaway should probably be:

  • Many NumPy functions just delegate to a method of the object passed in, so there can be huge differences when you pass in different objects.
  • Profiling, especially line-profiling, can be a great tool to find the places where the performance difference comes from.
  • Always make sure to test differently sized objects in such cases. You could be comparing constant factors that probably don't matter except if you process lots of small arrays.

Used versions:

Python 3.6.3 64-bit on Windows 10 Numpy 1.13.3 Pandas 0.21.1 

Answers 2

Just read the source code, it's clear.

def clip(a, a_min, a_max, out=None):     """a : array_like Array containing elements to clip."""     return _wrapfunc(a, 'clip', a_min, a_max, out=out)  def _wrapfunc(obj, method, *args, **kwds):     try:         return getattr(obj, method)(*args, **kwds)     #This situation has occurred in the case of     # a downstream library like 'pandas'.     except (AttributeError, TypeError):         return _wrapit(obj, method, *args, **kwds)  def _wrapit(obj, method, *args, **kwds):     try:         wrap = obj.__array_wrap__     except AttributeError:         wrap = None     result = getattr(asarray(obj), method)(*args, **kwds)     if wrap:         if not isinstance(result, mu.ndarray):             result = asarray(result)         result = wrap(result)     return result 

rectify:

after pandas v0.13.0_ahl1,pandas has it's own implement of clip.

Answers 3

There are two parts to the performance difference to be aware of here:

  • Python overhead in each library (pandas being extra helpful)
  • Difference in numeric algorithm implementation (pd.clip actually calls np.where)

Running this on a very small array should demonstrate the difference in Python overhead. For numpy, this is understandably very small, however pandas does a lot of checking (null values, more flexible argument processing, etc) before getting to the heavy number crunching. I've tried to show a rough breakdown of the stages which the two codes go through before hitting C code bedrock.

data = pd.Series(np.random.random(100)) 

When using np.clip on an ndarray, the overhead is simply the numpy wrapper function calling the object's method:

>>> %timeit np.clip(data.values, 0.2, 0.8)        # numpy wrapper, calls .clip() on the ndarray >>> %timeit data.values.clip(0.2, 0.8)            # C function call  2.22 µs ± 125 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) 1.32 µs ± 20.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) 

Pandas spends more time checking for edge cases before getting to the algorithm:

>>> %timeit np.clip(data, a_min=0.2, a_max=0.8)   # numpy wrapper, calls .clip() on the Series >>> %timeit data.clip(lower=0.2, upper=0.8)       # pandas API method >>> %timeit data._clip_with_scalar(0.2, 0.8)      # lowest level python function  102 µs ± 1.54 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) 90.4 µs ± 1.01 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) 73.7 µs ± 805 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) 

Relative to overall time, the overhead of both libraries before hitting C code is pretty significant. For numpy, the single wrapping instruction takes as much time to execute as the numeric processing. Pandas has ~30x more overhead just in the first two layers of function calls.

To isolate what is happening at the algorithm level, we should check this on a larger array and benchmark the same functions:

>>> data = pd.Series(np.random.random(1000000))  >>> %timeit np.clip(data.values, 0.2, 0.8) >>> %timeit data.values.clip(0.2, 0.8)  2.85 ms ± 37.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) 2.85 ms ± 15.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)  >>> %timeit np.clip(data, a_min=0.2, a_max=0.8) >>> %timeit data.clip(lower=0.2, upper=0.8) >>> %timeit data._clip_with_scalar(0.2, 0.8)  12.3 ms ± 135 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) 12.3 ms ± 115 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) 12.2 ms ± 76.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) 

The python overhead in both cases is now negligible; time for wrapper functions and argument checking is small relative to the calculation time on 1 million values. However there is a 3-4x speed difference which can be attributed to numeric implementation. By investigating a bit in the source code, we see that the pandas implementation of clip actually uses np.where, not np.clip:

def clip_where(data, lower, upper):     ''' Actual implementation in pd.Series._clip_with_scalar (minus NaN handling). '''     result = data.values     result = np.where(result >= upper, upper, result)     result = np.where(result <= lower, lower, result)     return pd.Series(result)  def clip_clip(data, lower, upper):     ''' What would happen if we used ndarray.clip instead. '''     return pd.Series(data.values.clip(lower, upper)) 

The additional effort required to check each boolean condition separately before doing a conditional replace would seem to account for the speed difference. Specifying both upper and lower would result in 4 passes through the numpy array (two inequality checks and two calls to np.where). Benchmarking these two functions shows that 3-4x speed ratio:

>>> %timeit clip_clip(data, lower=0.2, upper=0.8) >>> %timeit clip_where(data, lower=0.2, upper=0.8)  11.1 ms ± 101 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) 2.97 ms ± 76.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) 

I'm not sure why the pandas devs went with this implementation. np.clip may be a newer API function that previously required a workaround. There is also a little more to it than I've gone into here, since pandas checks for various case before running the final algorithm, and this is only one of the implementations that may be called.

Answers 4

The reason why the performance differs is because numpy first tends to search for pandas implementation of the function using getattr than doing the same in builtin numpy functions when a pandas object is passed.

Its not the numpy over the pandas object that is slow, its the pandas version.

When you do

np.clip(pd.Series([1,2,3,4,5]),a_min=None,amax=1)   

_wrapfunc is being called :

# Code from source  def _wrapfunc(obj, method, *args, **kwds):     try:         return getattr(obj, method)(*args, **kwds) 

Due to _wrapfunc's getattr method :

getattr(pd.Series([1,2,3,4,5]),'clip')(None, 1) # Equivalent to `pd.Series([1,2,3,4,5]).clip(lower=None,upper=1)` # 0    1 # 1    1 # 2    1 # 3    1 # 4    1 # dtype: int64 

If you go through the pandas implementation there is a lot of pre checking work that is done. Its the reason why the functions which has the pandas implementation done via numpy has such difference in speed.

Not only clip, functions like cumsum,cumprod,reshape,searchsorted,transpose and much more uses pandas version of them than numpy when you pass them a pandas object.

It might appear numpy is doing the work over those objects but under the hood its the pandas function.

Read More