Skip to contentSkip to conversation

tools/kvm_stat: misc changes

PATCH Applied Marc Hartmayer 2 participants 7 messages Jan 9, 2018 – Jan 12, 2018 KVM

lore
Share & tools
lore
#0 lore raw

cover tools/kvm_stat: misc changes

This patch series doesn't change any functionality, but simplifies the code.

Marc Hartmayer (4):
tools/kvm_stat: simplify the sortkey function tools/kvm_stat: use a namedtuple for storing the values tools/kvm_stat: use a more pythonic way to iterate over dictionaries tools/kvm_stat: avoid 'is' for equality checks

 tools/kvm/kvm_stat/kvm_stat | 65 +++++++++++++++++++++------------------------
 1 file changed, 30 insertions(+), 35 deletions(-)
Signature · 1 line
2.13.4
#1 lore raw

PATCH 1/4 tools/kvm_stat: simplify the sortkey function

The 'sortkey' function references a value in its enclosing scope (closure). This is not common practice for a sort key function so let's replace it. Additionally, the function 'sorted' has already a parameter for reversing the result therefore the inversion of the values is unneeded. The check for stats[x][1] is also superfluous as it's ensured that this value is initialized with 0.

---
 tools/kvm/kvm_stat/kvm_stat | 23 ++++++++---------------
 1 file changed, 8 insertions(+), 15 deletions(-)
tools/kvm/kvm_stat/kvm_stat +8 -15
index a5684d0968b4..d630f5f3e091 100755
@@ -1080,30 +1080,23 @@ class Tui(object):
         self.screen.move(row, 0)
         self.screen.clrtobot()
         stats = self.stats.get(self._display_guests)
-
-        def sortCurAvg(x):
-            # sort by current events if available
-            if stats[x][1]:
-                return (-stats[x][1], -stats[x][0])
-            else:
-                return (0, -stats[x][0])
-
-        def sortTotal(x):
-            # sort by totals
-            return (0, -stats[x][0])
         total = 0.
         for key in stats.keys():
             if key.find('(') is -1:
                 total += stats[key][0]
         if self._sorting == SORT_DEFAULT:
-            sortkey = sortCurAvg
+            def sortkey((_k, v)):
+                # sort by (delta value, overall value)
+                return (v[1], v[0])
         else:
-            sortkey = sortTotal
+            def sortkey((_k, v)):
+                # sort by overall value
+                return v[0]
+
         tavg = 0
-        for key in sorted(stats.keys(), key=sortkey):
+        for key, values in sorted(stats.items(), key=sortkey, reverse=True):
             if row >= self.screen.getmaxyx()[0] - 1:
                 break
-            values = stats[key]
             if not values[0] and not values[1]:
                 break
             if values[0] is not None:
Signature · 1 line
2.13.4
#2 lore raw

PATCH 2/4 tools/kvm_stat: use a namedtuple for storing the values

In reply to Marc Hartmayer

Use a namedtuple for storing the values as it allows to access the fields of a tuple via names. This makes the overall code much easier to read and to understand. Access by index is still possible as before.

---
 tools/kvm/kvm_stat/kvm_stat | 27 +++++++++++++++------------
 1 file changed, 15 insertions(+), 12 deletions(-)
tools/kvm/kvm_stat/kvm_stat +15 -12
index d630f5f3e091..2b7e83a5f7b8 100755
@@ -33,7 +33,7 @@ import resource
 import struct
 import re
 import subprocess
-from collections import defaultdict
+from collections import defaultdict, namedtuple
 
 VMX_EXIT_REASONS = {
     'EXCEPTION_NMI':        0,
@@ -800,6 +800,9 @@ class DebugfsProvider(Provider):
         self.read(2)
 
 
+EventStat = namedtuple('EventStat', ['value', 'delta'])
+
+
 class Stats(object):
     """Manages the data providers and the data they provide.
 
@@ -867,10 +870,10 @@ class Stats(object):
         for provider in self.providers:
             new = provider.read(by_guest=by_guest)
             for key in new if by_guest else provider.fields:
-                oldval = self.values.get(key, (0, 0))[0]
+                oldval = self.values.get(key, EventStat(0, 0)).value
                 newval = new.get(key, 0)
                 newdelta = newval - oldval
-                self.values[key] = (newval, newdelta)
+                self.values[key] = EventStat(newval, newdelta)
         return self.values
 
     def toggle_display_guests(self, to_pid):
@@ -1083,28 +1086,28 @@ class Tui(object):
         total = 0.
         for key in stats.keys():
             if key.find('(') is -1:
-                total += stats[key][0]
+                total += stats[key].value
         if self._sorting == SORT_DEFAULT:
             def sortkey((_k, v)):
                 # sort by (delta value, overall value)
-                return (v[1], v[0])
+                return (v.delta, v.value)
         else:
             def sortkey((_k, v)):
                 # sort by overall value
-                return v[0]
+                return v.value
 
         tavg = 0
         for key, values in sorted(stats.items(), key=sortkey, reverse=True):
             if row >= self.screen.getmaxyx()[0] - 1:
                 break
-            if not values[0] and not values[1]:
+            if not values.value and not values.delta:
                 break
-            if values[0] is not None:
-                cur = int(round(values[1] / sleeptime)) if values[1] else ''
+            if values.value is not None:
+                cur = int(round(values.delta / sleeptime)) if values.delta else ''
                 if self._display_guests:
                     key = self.get_gname_from_pid(key)
                 self.screen.addstr(row, 1, '%-40s %10d%7.1f %8s' %
-                                   (key, values[0], values[0] * 100 / total,
+                                   (key, values.value, values.value * 100 / total,
                                     cur))
                 if cur is not '' and key.find('(') is -1:
                     tavg += cur
@@ -1375,7 +1378,7 @@ def batch(stats):
         s = stats.get()
         for key in sorted(s.keys()):
             values = s[key]
-            print('%-42s%10d%10d' % (key, values[0], values[1]))
+            print('%-42s%10d%10d' % (key, values.value, values.delta))
     except KeyboardInterrupt:
         pass
 
@@ -1392,7 +1395,7 @@ def log(stats):
     def statline():
         s = stats.get()
         for k in keys:
-            print(' %9d' % s[k][1], end=' ')
+            print(' %9d' % s[k].delta, end=' ')
         print()
     line = 0
     banner_repeat = 20
Signature · 1 line
2.13.4
#3 lore raw

PATCH 3/4 tools/kvm_stat: use a more pythonic way to iterate over dictionaries

In reply to Marc Hartmayer

If it's clear that the values of a dictionary will be used then use the '.items()' method.

---
 tools/kvm/kvm_stat/kvm_stat | 19 +++++++++----------
 1 file changed, 9 insertions(+), 10 deletions(-)
tools/kvm/kvm_stat/kvm_stat +9 -10
index 2b7e83a5f7b8..c15950a6c4a4 100755
@@ -1084,9 +1084,10 @@ class Tui(object):
         self.screen.clrtobot()
         stats = self.stats.get(self._display_guests)
         total = 0.
-        for key in stats.keys():
+        for key, values in stats.items():
             if key.find('(') is -1:
-                total += stats[key].value
+                total += values.value
+
         if self._sorting == SORT_DEFAULT:
             def sortkey((_k, v)):
                 # sort by (delta value, overall value)
@@ -1376,8 +1377,7 @@ def batch(stats):
         s = stats.get()
         time.sleep(1)
         s = stats.get()
-        for key in sorted(s.keys()):
-            values = s[key]
+        for key, values in sorted(s.items()):
             print('%-42s%10d%10d' % (key, values.value, values.delta))
     except KeyboardInterrupt:
         pass
@@ -1385,17 +1385,16 @@ def batch(stats):
 
 def log(stats):
     """Prints statistics as reiterating key block, multiple value blocks."""
-    keys = sorted(stats.get().keys())
+    sorted_stats = sorted(stats.get().items())
 
     def banner():
-        for k in keys:
-            print(k, end=' ')
+        for key, _ in sorted_stats:
+            print(key, end=' ')
         print()
 
     def statline():
-        s = stats.get()
-        for k in keys:
-            print(' %9d' % s[k].delta, end=' ')
+        for _, values in sorted_stats:
+            print(' %9d' % values.delta, end=' ')
         print()
     line = 0
     banner_repeat = 20
Signature · 1 line
2.13.4
#4 lore raw

PATCH 4/4 tools/kvm_stat: avoid 'is' for equality checks

In reply to Marc Hartmayer

Use '==' for equality checks and 'is' when comparing identities.

An example where '==' and 'is' behave differently:

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

a = 4242
a == 4242

True

Quoted 1 line
Quoted 1 line
Quoted 1 line

a is 4242

False

---
 tools/kvm/kvm_stat/kvm_stat | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
tools/kvm/kvm_stat/kvm_stat +2 -2
index c15950a6c4a4..d40d22815aeb 100755
@@ -1085,7 +1085,7 @@ class Tui(object):
         stats = self.stats.get(self._display_guests)
         total = 0.
         for key, values in stats.items():
-            if key.find('(') is -1:
+            if key.find('(') == -1:
                 total += values.value
 
         if self._sorting == SORT_DEFAULT:
@@ -1110,7 +1110,7 @@ class Tui(object):
                 self.screen.addstr(row, 1, '%-40s %10d%7.1f %8s' %
                                    (key, values.value, values.value * 100 / total,
                                     cur))
-                if cur is not '' and key.find('(') is -1:
+                if cur != '' and key.find('(') == -1:
                     tavg += cur
             row += 1
         if row == 3:
Signature · 1 line
2.13.4
maintainer Applied
#5 lore raw
In reply to Marc Hartmayer
Quoted 12 lines · Marc Hartmayer

This patch series doesn't change any functionality, but simplifies the code.

Marc Hartmayer (4):
tools/kvm_stat: simplify the sortkey function tools/kvm_stat: use a namedtuple for storing the values tools/kvm_stat: use a more pythonic way to iterate over dictionaries tools/kvm_stat: avoid 'is' for equality checks

 tools/kvm/kvm_stat/kvm_stat | 65 +++++++++++++++++++++------------------------
 1 file changed, 30 insertions(+), 35 deletions(-)

Applied to kvm/queue, thanks.

Paolo

#6 lore raw
Quoted 10 lines · Paolo Bonzini
Quoted 9 lines · Marc Hartmayer

This patch series doesn't change any functionality, but simplifies the code.

Marc Hartmayer (4):
tools/kvm_stat: simplify the sortkey function tools/kvm_stat: use a namedtuple for storing the values tools/kvm_stat: use a more pythonic way to iterate over dictionaries tools/kvm_stat: avoid 'is' for equality checks

Quoted 5 lines
Quoted 3 lines
 tools/kvm/kvm_stat/kvm_stat | 65 +++++++++++++++++++++------------------------
 1 file changed, 30 insertions(+), 35 deletions(-)

Applied to kvm/queue, thanks.

Thanks.

Quoted 3 lines

Paolo

Signature · 8 lines
Beste Grüße / Kind regards
   Marc Hartmayer

IBM Deutschland Research & Development GmbH
Vorsitzende des Aufsichtsrats: Martina Koederitz
Geschäftsführung: Dirk Wittkopp
Sitz der Gesellschaft: Böblingen
Registergericht: Amtsgericht Stuttgart, HRB 243294