Skip to content

Instantly share code, notes, and snippets.

@philipbelesky
Created March 10, 2014 19:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save philipbelesky/9472982 to your computer and use it in GitHub Desktop.
Save philipbelesky/9472982 to your computer and use it in GitHub Desktop.
An attempt at easier GhPython Profiling
import rhinoscriptsyntax as rs
if debug:
# debug is a Boolean input I use for each GhPython component - it toggles messages/debug info
from System.Diagnostics import Stopwatch as sw
profiling = ['========']
timing = 0
total = sw.StartNew()
class Timer(object):
def __init__(self, message="", debug=True):
# the timing global keeps track of which level of timing we are running at so nested timers are possible
global timing
timing += 1
self.msg = message
self.debug = debug
def __enter__(self):
self.timer = sw.StartNew()
self.begun = self.timer.Elapsed
return self
def __exit__(self, *args):
if self.debug:
t = str(self.timer.Elapsed - self.begun)[-10:-4]
global timing
timing -= 1
global profiling
profiling.append("%s %s s to %s" % ("\t" * (timing), t, self.msg))
# Code goes here, with bits you want profile wrapped in a with
# Each Timer takes a message (ie what you are timing) as well as a override to the global debug value
with Timer("finish this example", debug) as t:
group_colors, group_regions = setup_bounding_boxes(search_groups)
with Timer() as t:
grid_coords = setup_grid(grid_rect)
with Timer("finish an example with nested timers ", debug) as t:
with Timer("create nested example one", debug) as t:
out_h, out_s, out_l = zip(*(item.get_hsl() for item in grid_coords))
with Timer("create nested example two", debug) as t:
[r_tree.Search(region['rg_box'], search_hit, i) for i, region in enumerate(group_regions)]
# This goes at the very end of the script
# As it prints out the results and the total time everything took
if debug:
profiling.append("========")
print '\n'.join(profiling)
print " %s s total" % str(total.Elapsed)[-10:-4]
# Console output looks something like this:
"""
========
00.279 finish this example
00.006 s to
00.023 s to finish an example with nested timers
00.013 s to create nested example one
00.010 s to create nested example two
========
00.443 s total
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment