def run_profile():
    import profile
    profile.run('for i in range(1): demo()', '/tmp/profile.out')
    import pstats
    p = pstats.Stats('/tmp/profile.out')
    p.strip_dirs().sort_stats('time', 'cum').print_stats(60)
    p.strip_dirs().sort_stats('cum', 'time').print_stats(60)
Example #2
0
def sortedProfiling(code, maxfunctions=50):
    f = "temp/profilingInfo.tmp"
    if os.path.split(os.path.abspath(""))[1] != "tests":
        f = "../" + f
    profile.run(code, f)
    p = pstats.Stats(f)
    p.sort_stats("time").print_stats(maxfunctions)
Example #3
0
def _main():
    """Run from command line."""
    usage = "usage: %prog [options] cmd [arg] ..."
    optprs = OptionParser(usage=usage, version=version)

    optprs.add_option("--debug", dest="debug", default=False,
                      action="store_true",
                      help="Enter the pdb debugger on main()")
    optprs.add_option("--host", dest="host", metavar="HOST",
                      default="localhost", help="Connect to server at HOST")
    optprs.add_option("--port", dest="port", type="int",
                      default=9000, metavar="PORT",
                      help="Connect to server at PORT")
    optprs.add_option("--profile", dest="profile", action="store_true",
                      default=False,
                      help="Run the profiler on main()")

    (options, args) = optprs.parse_args(sys.argv[1:])

    # Are we debugging this?
    if options.debug:
        import pdb

        pdb.run('main(options, args)')

    # Are we profiling this?
    elif options.profile:
        import profile

        print("%s profile:" % sys.argv[0])
        profile.run('main(options, args)')

    else:
        main(options, args)
Example #4
0
def test():
    import profile, pstats

    # profile.run("simple_test()")
    profile.run("stacked_test()", "barchart.prof")
    p = pstats.Stats("barchart.prof")
    p.sort_stats("cumulative").print_stats(20)
Example #5
0
 def opt_profile(option, opt, value, parser):
     global profiling
     if not profiling:
         profiling = 1
         import profile
         profile.run('SCons.Script.main()', value)
         sys.exit(exit_status)
Example #6
0
def sortedProfiling(code, maxfunctions=50):
    f = 'temp/profilingInfo.tmp'
    if os.path.split(os.path.abspath(''))[1] != 'tests':
        f = '../' + f
    profile.run(code, f)
    p = pstats.Stats(f)
    p.sort_stats('time').print_stats(maxfunctions)
Example #7
0
def reference_viewer(sys_argv):
    """Create reference viewer from command line."""
    viewer = ReferenceViewer(layout=default_layout)
    viewer.add_default_plugins()
    viewer.add_separately_distributed_plugins()

    # Parse command line options with optparse module
    from optparse import OptionParser

    usage = "usage: %prog [options] cmd [args]"
    optprs = OptionParser(usage=usage,
                          version=('%%prog %s' % version.version))
    viewer.add_default_options(optprs)

    (options, args) = optprs.parse_args(sys_argv[1:])

    if options.display:
        os.environ['DISPLAY'] = options.display

    # Are we debugging this?
    if options.debug:
        import pdb

        pdb.run('viewer.main(options, args)')

    # Are we profiling this?
    elif options.profile:
        import profile

        print(("%s profile:" % sys_argv[0]))
        profile.run('viewer.main(options, args)')

    else:
        viewer.main(options, args)
Example #8
0
def main():
    import profile
    import pstats

    if len(sys.argv[1:]):
        profile_it = 0
        reps_flag = 0
        profile_reps = 100
        for arg in sys.argv[1:]:
            if reps_flag:
                profile_reps = int(arg)
                reps_flag = 0
            elif arg == "-p" or arg == "--profile":
                profile_it = 1
            elif arg == "-r" or arg == "--reps":
                reps_flag = 1
            elif profile_it > 0:
                print "Profiling, " + str(profile_reps) + " repetitions..."
                page = page_factory.page(arg)
                profile.run('benchmark("' + arg + '", ' + str(profile_reps) + ")", "profile_stats")
                p = pstats.Stats("profile_stats")
                p.sort_stats("time").print_stats()
            else:
                print page_factory.page(URI(arg))
    else:
        profile()
def prof_run(fun,file,n):
    '''Run function fun, put the stats into file and print
    out the stats for the n most time consuming operations.'''
    profile.run(fun,file)
    prof_dat = pstats.Stats(file)
    prof_dat.strip_dirs().sort_stats('time').print_stats(n)
    return
Example #10
0
def runtests(xmlrunner=False):
   ''' Run unit tests '''
   import sys

   if '--profile' in sys.argv:
       import profile
       import pstats

       sys.argv = [x for x in sys.argv if x != '--profile']

       if xmlrunner:
           import xmlrunner as xr
           profile.run("unittest.main(testRunner=xr.XMLTestRunner(output='test-reports', verbosity=2))", '_stats.txt')
       else:
           profile.run('unittest.main()', '_stats.txt')

       stats = pstats.Stats('_stats.txt')
       #stats.strip_dirs()
       stats.sort_stats('cumulative', 'calls')
       stats.print_stats(25)
       stats.sort_stats('time', 'calls')
       stats.print_stats(25)

   elif xmlrunner:
       import xmlrunner as xr
       unittest.main(testRunner=xr.XMLTestRunner(output='test-reports', verbosity=2)) 

   else:
       unittest.main()
Example #11
0
    def run_profile(self):
        using_hotshot = False

        if using_hotshot:
            import hotshot
            import hotshot.stats
        else:
            import profile
            import pstats
        profile_name = 'NormalFormTest.prof'
        proportion_worst_results = 0.125

        create_empty_file(profile_name)
    
        if using_hotshot:
            profiler = hotshot.Profile(profile_name)
            benchtime = profiler.runcall(run_nf) #main call
            profiler.close()
            stats = hotshot.stats.load(profile_name)
        else:
            profile.run('run_nf()', profile_name) #main call
            stats = pstats.Stats(profile_name)

        #output profile
        stats.strip_dirs()
        stats.sort_stats('time', 'cum', 'calls')
        print '[1] Statistics:'
        stats.print_stats(proportion_worst_results)
        print '[2] Callers for the above:'
        stats.print_callers(proportion_worst_results)
def beltway_profiling(algorithm, input_size_step=5, max_input_size=50):
  """ Perform a profiling session on a solution algorithm for the beltway problem.
      :param algorithm: The candidate algorithm to solve beltway problem:
                        A function that takes a list of distances and return a list of points.
                        The algorithm will be first profiled on a input set of 10 points,
                        successive profiling will involve input set with size that will be incremented 
                        by 'input_size_step' points at each step, until the max_input_size is reached.
                        
      :type algorithm: function
      :param input_size_step: how many points are added in each profiling step
      :type input_size_step: int
      :invariant: input_size_step > 0
      :param max_input_size: Maximum number of points in any problem instance
      :type max_input_size: int
      :invariant: max_input_size > 10

      :return: None
  """     
  if input_size_step <= 0 or max_input_size < 10:
    logging.warn("[beltway_profiling] Illegal parameters input_size_step: %s, max_input_size: %s" % (str(input_size_step), str(max_input_size)))
    
    

  import profile    #import profile only if this method is called
  pr = profile.Profile()
    
  for _ in range(5):
      print pr.calibrate(10000)
  for n_points in xrange(10, max_input_size, input_size_step):
    profile.run('beltway_random_testing(algorithm, 1000, %d, %d)' % (n_points, n_points), 'beltway_profile_%d.txt' % n_points)        
Example #13
0
 def main(self, *arguments):
     import getopt
     options, arguments = getopt.getopt(arguments, 'bipqv')
     for option, value in options:
         if option == '-b':
             self.bigger = True
         elif option == '-i':
             self.immediate = True
         elif option == '-p':
             self.profile = True
         elif option == '-q':
             self.verbosity = 0
         elif option == '-v':
             self.verbosity = 2
     self.print_warning()
     # Save remaining arguments for `unittest' to consider.
     sys.argv[1:] = list(arguments)
     self.prepare_suite()
     if self.profile:
         import profile, pstats
         global run_suite
         run_suite = self.run_suite
         profile.run('run_suite()', 'profile-data')
         stats = pstats.Stats('profile-data')
         stats.strip_dirs().sort_stats('time', 'cumulative').print_stats(10)
     else:
         self.run_suite()
Example #14
0
def planner(sys_argv):

    viewer = QueuePlanner(layout=default_layout)
    viewer.add_plugins(plugins)

    # Parse command line options with optparse module
    from optparse import OptionParser

    usage = "usage: %prog [options] cmd [args]"
    optprs = OptionParser(usage=usage,
                          version=('%%prog %s' % version.version))
    viewer.add_default_options(optprs)

    (options, args) = optprs.parse_args(sys_argv[1:])

    if options.display:
        os.environ['DISPLAY'] = options.display

    # Are we debugging this?
    if options.debug:
        import pdb

        pdb.run('viewer.main(options, args)')

    # Are we profiling this?
    elif options.profile:
        import profile

        print(("%s profile:" % sys_argv[0]))
        profile.run('viewer.main(options, args)')

    else:
        viewer.main(options, args)
	def __call__(self, **kwargs):
		
		#profile.run('ap_rigging.%s(%s)' % (self.f, kwargs), 'C:/temp/profile.txt')
		profile.run('%s(%s)' % (self.f, kwargs), 'C:/temp/profile.txt')
		import pstats
		p = pstats.Stats('C:/temp/profile.txt')
		p.sort_stats('cumulative').print_stats(10)
Example #16
0
def profile():
    import profile, testing
    profile.run('testing.compile()', 'profile.txt')
    import pstats
    p = pstats.Stats('profile.txt')
    #p.strip_dirs().sort_stats('cumulative').print_stats(20)
    p.strip_dirs().sort_stats('time').print_stats(20)
Example #17
0
def profile():
    import profile, pstats
    path = "/tmp/profile"
    profile.run( "profile_execute()", path)
    p = pstats.Stats(path)
    p.sort_stats('cumulative').print_stats(30)
    print "*"*30
    p.sort_stats('time').print_stats(30)
Example #18
0
def test_speed(rsa, dgst):
    print '  measuring speed...'
    if showprofile:
        import profile
        profile.run('speed()')
    else:
        speed()
        print
Example #19
0
def mainprofile():
    import profile
    pf = 'profile_results'
    profile.run('main()', pf)
    import pstats
    p = pstats.Stats(pf)
    p.sort_stats('cumulative').print_stats(50)
    os.unlink(pf)
Example #20
0
def StartPIS():
    """ Prepare and enter project insight studio.
    1) First thing is to process the command line  as following.
    Usage: PIS.py [options]
    
    Options:
      --version             show program's version number and exit
      -h, --help            show this help message and exit
      -p PROFILE_NAME, --profile=PROFILE_NAME
                            Specific profile file name for getting profiling
                            information
      -d VERBOSE, --debug=VERBOSE
                            Turn on debug message and specific debug level:
                            [DEBUG|INFO|WARNING|ERROR|CRITICAL]
      -l LOGFILE, --logfile=LOGFILE
                            Specific log file or server address to hold log
                            information under specific debug level.
      -s LOGSERVER, --logserver=LOGSERVER
                            Specific log server address to hold log information
                            under specific debug level.  
                            
    2) Initialize logging system as early as possible.
    3) Launch the PIS's core.  
    """
    #
    # Process command line firstly.
    #
    parser = OptionParser(version="%s - Version %s" % (PROJECT_NAME, VERSION))
    parser.add_option('-p', '--profile', action='store', dest='profile_name',
                      help='Specific profile file name for getting profiling information')
    parser.add_option('-d', '--debug', action='store', dest='verbose', default='DEBUG',
                      help='Turn on debug message and specific debug level: [DEBUG|INFO|WARNING|ERROR|CRITICAL]')
    parser.add_option('-l', '--logfile', action='store', dest='logfile',
                      help='Specific log file or server address to hold log information under specific debug level.')
    parser.add_option('-s', '--logserver', action='store', dest='logserver',
                      help='Specific log server address to hold log information under specific debug level.')
    
    (options, args) = parser.parse_args()
    
    if options.verbose not in ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']:
        parser.error("invalid value for -d options")
        sys.exist(0)
    
    #
    # Enable the logging system.
    #
    core.debug.IniLogging(options.verbose, options.logfile, options.logserver)
    
    #
    # Start main entry, if want profiling, then profile the main entry.
    #
    if options.profile_name != None and gFlagProfileEnable:
        # profiling PIS and display the result after finishing run()
        profile.run('core.appmain.main()', options.profile_name)
        stats = pstats.Stats(options.profile_name)
        stats.strip_dirs().sort_stats("time").print_stats(10)
    else:
        core.appmain.main()
Example #21
0
def profile(num):
##     import cProfile
##     profiler = cProfile
    profiler.run("[run(root) for x in range(0,100)]", 'logfile.dat')
    stats = pstats.Stats('logfile.dat')
    stats.strip_dirs()
    stats.sort_stats('cumulative', 'calls')
    #stats.sort_stats('calls')
    stats.print_stats(num)
Example #22
0
def profile(statement):
	import profile, pstats
	datafile = 'meta/profile.data'
	statfile = 'meta/profile.output'
	profile.run('main()', datafile)
	with open(statfile, 'w') as stream:
		p = pstats.Stats(datafile, stream=stream)
		p.strip_dirs().sort_stats('cumulative')
		p.print_stats()
def run_profile():
    import profile

    profile.run("for i in range(10): demo()", "/tmp/profile.out")
    import pstats

    p = pstats.Stats("/tmp/profile.out")
    p.strip_dirs().sort_stats("time", "cum").print_stats(60)
    p.strip_dirs().sort_stats("cum", "time").print_stats(60)
Example #24
0
def speedTest():
    global x
    import profile
    M.compilestring(factorial)
    M.compilestring("START " +
                    20 * "50 FACTORIAL DROP " +
                    "STOP")
    x = M.Thread()
    profile.run('for i in range(1000): x.run()')
Example #25
0
 def runProfile(command):
   import random
   random.seed(23)
   import profile, pstats
   datFile = '%s.prof.dat' % (command)
   profile.run('%s()' % command, datFile)
   stats = pstats.Stats(datFile)
   stats.strip_dirs()
   stats.sort_stats('time').print_stats()
 def profiler():
     import profile,pstats
     def benchmark(): #todo
         pass
     filename = 'benchmark.prof'
     profile.run("benchmark()",filename)
     s = pstats.Stats(filename)
     s.sort_stats("cumulative")
     s.print_stats("getitem|setitem|append|pop|insert")
Example #27
0
def prof_test():
    sys.stdout.write("\n$PY_DEBUG_OBJECT is: ")
    if os.environ.has_key("PY_DEBUG_OBJECT"):
        sys.stdout.write(os.environ["PY_DEBUG_OBJECT"])
    else:
        sys.stdout.write("not defined")
    sys.stdout.write("\n\n")

    sys.stdout.write("Profiling speed of Object constructor/get/set.\n\n")
    profile.run("profObject(1000)")
Example #28
0
def prof(dfile):
  global f
  import profile
  f=open(dfile)
  #profile.run( "do_it()", 'profile.out' )
  do_it(); return
  profile.run( "do_it()" )
  #stats = profile.Stats( 'profile.out' )
  #stats.print_stats()
  tr.free()
Example #29
0
def startProfile(filename=PyUtilProfileDefaultFilename,
                 lines=PyUtilProfileDefaultLines,
                 sorts=PyUtilProfileDefaultSorts,
                 silent=0,
                 callInfo=1,
                 cmd='run()'):
    import profile
    profile.run(cmd, filename)
    if not silent:
        printProfile(filename, lines, sorts, callInfo)
Example #30
0
 def test2(self):
     "This is a profiled version of test1()."
     try:
         import profile
     except ImportError:
         return
     fileName = outputfile('test_graphics_speed_profile.log')
     # This runs ok, when only this test script is executed,
     # but fails, when imported from runAll.py...
     profile.run("t = GraphicsSpeedTestCase('test2')", fileName)
Example #31
0
#sys.path.append(os.path.abspath('..'))#this is a hack because Eclipse has bug

from vimm.Frame import Frame


def Main():
    app = wx.PySimpleApp()
    frame = Frame(None, -1, 'vimm')
    frame.Show()
    if len(sys.argv) > 1:
        fname = sys.argv[1]
        frame.load_file_nodialog(fname)
    else:
        #frame.load_file_nodialog("../testfiles/CSF_SPECT_aluminum.nc")
        #frame.load_file_nodialog("../testfiles/o2.molf")
        frame.create_xyz_file()
        #frame.dotest()
    app.MainLoop()


if __name__ == '__main__':
    do_profile = 0
    if do_profile:
        import profile, pstats
        profile.run('Main()', 'vimm_prof')
        vimm_prof = pstats.Stats('vimm_prof')
        vimm_prof.strip_dirs().sort_stats('time').print_stats(20)
    else:
        Main()
    #end
Example #32
0
    return T.weight + min([min_length(s) for s in T.sons] or [0])


if __name__ == "__main__":
    example_1 = Tree(0, [
        Tree(5, [Tree(-4, [Tree(11), Tree(2)]),
                 Tree(2)]),
        Tree(2, [Tree(5, [Tree(-2), Tree(4), Tree(7)])]),
        Tree(1, [Tree(10)])
    ])

    example_2 = Tree(5, [
        Tree(1, [
            Tree(-5, [Tree(7, []), Tree(3, [])]),
            Tree(2, []),
            Tree(11, [Tree(-5, [])])
        ]),
        Tree(2, [Tree(0, [Tree(12, [])])]),
        Tree(3, [Tree(7, [Tree(2, [])]), Tree(2, [])])
    ])

    print("## Example 1:")
    print("Min length: %d" % min_length(example_1))
    print("Size: %d" % example_1.size())
    profile.run("min_length(example_1)")

    print("\n## Example 2:")
    print("Min length: %d" % min_length(example_2))
    print("Size: %d" % example_2.size())
    profile.run("min_length(example_2)")
Example #33
0
File: Pi.py Project: vicmatmar/Pi
def main():

    profile.run('IsPrimeNumberRangeChecker(3, 10000000)')
Example #34
0
            #self.putchar('\n')


def deroff_files(files):
    for arg in files:
        sys.stderr.write(arg + '\n')
        if arg.endswith('.gz'):
            f = gzip.open(arg, 'r')
            str = f.read()
            if IS_PY3: str = str.decode('latin-1')
        else:
            f = open(arg, 'r')
            str = f.read()
        d = Deroffer()
        d.deroff(str)
        d.flush_output(sys.stdout)
        f.close()


if __name__ == "__main__":
    import gzip
    paths = sys.argv[1:]
    if True:
        deroff_files(paths)
    else:
        import cProfile, profile, pstats
        profile.run('deroff_files(paths)', 'fooprof')
        p = pstats.Stats('fooprof')
        p.sort_stats('time').print_stats(100)
        #p.sort_stats('calls').print_callers(.5, 'startswith')
Example #35
0
	def profileb3():
	    profile.run(mainfunction, output)
Example #36
0
        import ftp_server
        import chat_server
        import resolver
        import logger
        rs = resolver.caching_resolver ('127.0.0.1')
        lg = logger.file_logger (sys.stdout)
        ms = monitor.secure_monitor_server ('fnord', '127.0.0.1', 9999)
        fs = filesys.os_filesystem (sys.argv[1])
        dh = default_handler.default_handler (fs)
        hs = http_server ('', string.atoi (sys.argv[2]), rs, lg)
        hs.install_handler (dh)
        ftp = ftp_server.ftp_server (
                ftp_server.dummy_authorizer(sys.argv[1]),
                port=8021,
                resolver=rs,
                logger_object=lg
                )
        cs = chat_server.chat_server ('', 7777)
        sh = status_handler.status_extension([hs,ms,ftp,cs,rs])
        hs.install_handler (sh)
        if ('-p' in sys.argv):
            def profile_loop ():
                try:
                    asyncore.loop()
                except KeyboardInterrupt:
                    pass
            import profile
            profile.run ('profile_loop()', 'profile.out')
        else:
            asyncore.loop()
Example #37
0
        else:
            print "Incorrect status_code {} for url {}".format(r.status_code,url)
    except Exception as inst:
        if verbose:
            print "Download failed from url {}.".format(url)
            print inst 
    return None

def get_SHA1_b64_from_URL(url,verbose=False):
    if verbose:
        print "Downloading image from {}.".format(url)
    try:
        r = requests.get(url, stream=True, timeout=imagedltimeout)
        if r.status_code == 200:
            sha1hash = get_SHA1_from_data(r.raw.data)
            b64_from_data = get_b64_from_data(r.raw.data)
            return sha1hash,b64_from_data
    except Exception as inst:
        if verbose:
            print "Download failed from url {}.".format(url)
            print inst 
        return None,None

if __name__ == "__main__":
    import profile
    profile.run('sha1 = get_SHA1_from_URL("https://s3.amazonaws.com/memex-images/full/581ed33d3e12498f12c86b44010306b172f4ad6a.jpg")')
    print sha1
    profile.run('sha1_sio = get_SHA1_from_URL_StringIO("https://s3.amazonaws.com/memex-images/full/581ed33d3e12498f12c86b44010306b172f4ad6a.jpg")')
    print sha1_sio
    sha1_sio = get_SHA1_from_URL_StringIO("https://s3.amazonaws.com/memex-images/full/581ed33d3e12498f12c86b44010306b172f4ad6a.jpg")
    print sha1_sio
Example #38
0
##         sys.argv = ["macgrins", fss.as_pathname()]
##     else:
##         import EasyDialogs
##         url = EasyDialogs.AskString("CMIF/SMIL URL")
##         if url is None:
##             sys.exit(0)
##         sys.argv = ["maccmifed", url]

no_exception=0
try:
    try:
        if profile:
            import profile
            fss, ok = macfs.StandardPutFile("Profile output:")
            if not ok: sys.exit(1)
            profile.run("import cmifed", fss.as_pathname())
        else:
            import cmifed
        no_exception=1
    except SystemExit:
        no_exception=1
finally:
    if not no_exception:
        if quietconsole:
            quietconsole.revert()
##         if DEBUG:
##             import pdb
##             pdb.post_mortem(sys.exc_info()[2])
##         elif quietconsole:
##             quietconsole.revert()
##             print 'Type return to exit-',
Example #39
0
        nsv2 = _hyperplane(hyp_x_max, self._w, self._b, -1)
        self._ax.plot([hyp_x_min, hyp_x_max], [nsv1, nsv2], 'k')

        db1 = _hyperplane(hyp_x_min, self._w, self._b, 0)
        db2 = _hyperplane(hyp_x_max, self._w, self._b, 0)
        self._ax.plot([hyp_x_min, hyp_x_max], [db1, db2], 'y--')

        plt.show()


data_dict = {
    -1: np.array([
        [1, 7],
        [2, 8],
        [3, 8],
    ]),
    1: np.array([
        [5, 1],
        [6, -1],
        [7, 3],
    ])
}

if __name__ == '__main__':
    svm = SupportVectorMachine()
    profile.run('svm.fit(data_dict)')
    predict_us = [[0, 10], [1, 3], [3, 4], [3, 5], [5, 5], [5, 6], [6, -5],
                  [5, 8]]
    for p in predict_us:
        svm.predict(p)
    svm.visualize()
Example #40
0
def profileProfile():
    print "using standard profiler"
    import profile
    profile.run('bomberman.main()', PROFILEFILE)
Example #41
0
#
#  Copyright 2001 - 2016 Ludek Smid [http://www.ospace.net/]
#
#  This file is part of Pygame.UI.
#
#  Pygame.UI is free software; you can redistribute it and/or modify
#  it under the terms of the Lesser GNU General Public License as published by
#  the Free Software Foundation; either version 2.1 of the License, or
#  (at your option) any later version.
#
#  Pygame.UI is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  Lesser GNU General Public License for more details.
#
#  You should have received a copy of the Lesser GNU General Public License
#  along with Pygame.UI; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#

# profiling
import profile
profile.run('import demo', 'profile.txt')
Example #42
0
			self.HDICT[key] = [item]
		pass


	
	def testit(self):
		while 1:
			a = util.getinput("Enter a word:")
			if a=='.': break
			if a=='': continue

			self.search_prn(a)
	

if __name__ == "__main__":
	if os.getenv("SHELL") != None:
		hdic = hanengdict("/data1/AD/data/engdic/")
	else:
		hdic = hanengdict("C:/Works/ad_svc_backup/ad_svc_data/engdic/")

	profile.run ("hdic.prepare('a', 'a')")

	hdic.info()
	#hdic.prn_hdict()
	#hdic.prn_edict()

	hdic.testit()



Example #43
0
    book.set_price(9999)

    book = inven.find("mybook0123")
    if book:
        book.show()
    else:
        print "Not in the inventory"
    print

    print "# Test 3"
    inven.remove("mybook0123")  # implement BookInventory.remove()
    book = inven.find("mybook0123")
    if book:
        book.show()
    else:
        print "Not in the inventory"
    print

    print "# Test 4"
    pf.run('find_book_ntimes(inven, "mybook0000", 10000)'
           )  # performance evaluation of sequential search
    pf.run('find_book_ntimes(inven, "mybook0123", 10000)'
           )  # *this book is not in the inventory
    pf.run('find_book_ntimes(inven, "mybook9999", 10000)')

    print "# Test 4 - bsearch"
    pf.run('find_bsearch_book_ntimes(inven, "mybook0000", 10000)'
           )  # implement BookInventory.find_bsearch()
    pf.run('find_bsearch_book_ntimes(inven, "mybook0123", 10000)')
    pf.run('find_bsearch_book_ntimes(inven, "mybook9999", 10000)')
                      default=False,
                      help="Run as a server")
    parser.add_option("--svcname",
                      dest="svcname",
                      default='ro_example',
                      help="Register using service NAME",
                      metavar="NAME")

    (options, args) = parser.parse_args(sys.argv[1:])

    if len(args) != 0:
        parser.error("incorrect number of arguments")

    # Are we debugging this?
    if options.debug:
        import pdb

        pdb.run('main(options, args)')

    # Are we profiling this?
    elif options.profile:
        import profile

        print "%s profile:" % sys.argv[0]
        profile.run('main(options, args)')

    else:
        main(options, args)

#END
NETGEN_3D_Parameters.SetOptimize( 1 )
NETGEN_3D_Parameters.SetFineness( 2 )
NETGEN_3D_Parameters.SetMinSize( 1 )
fluid_1 = Mesh_1.GroupOnGeom(fluid,'fluid',SMESH.VOLUME)
solid_1 = Mesh_1.GroupOnGeom(solid,'solid',SMESH.VOLUME)
wall_1 = Mesh_1.GroupOnGeom(wall,'wall',SMESH.FACE)
inlet_1 = Mesh_1.GroupOnGeom(inlet,'inlet',SMESH.FACE)
outlet_1 = Mesh_1.GroupOnGeom(outlet,'outlet',SMESH.FACE)
isDone = Mesh_1.Compute()

## set object names
smesh.SetName(Mesh_1.GetMesh(), 'Mesh_1')
smesh.SetName(NETGEN_2D3D.GetAlgorithm(), 'NETGEN_2D3D')
smesh.SetName(NETGEN_3D_Parameters, 'NETGEN 3D Parameters')
smesh.SetName(fluid_1, 'fluid')
smesh.SetName(solid_1, 'solid')
smesh.SetName(wall_1, 'wall')
smesh.SetName(inlet_1, 'inlet')
smesh.SetName(outlet_1, 'outlet')

if salome.sg.hasDesktop():
  salome.sg.updateObjBrowser(1)

import salomeToOpenFOAM
import profile
profile.run("salomeToOpenFOAM.exportToFoam(Mesh_1,'./sampleMultiRegionPipe/constant/polyMesh')")
#salomeToOpenFOAM.exportToFoam(Mesh_1,'./sampleMultiRegionPipe/constant/polyMesh')

#Note that no internal BC has ben set up. splitMeshRegions -cellZones will create regeionX_to_regionY
#Boundaries.
#Testing script to run a bunch of different command line cases to ensure motionmeerkat functionality.
import os
import numpy as np
import profile
#cd into direction holding main.py - for users this would be the directory holding main.exe

### Profile Code
profile.run("os.system('main.py --minSIZE 0.3')")

# Run from command line, using default video to test state
testing_mainpy = False
if testing_mainpy:
    os.chdir('C:/Users/Ben/Documents/OpenCV_HummingbirdsMotion/MotionMeerkat/')

    #Minsize
    os.system('main.py --minSIZE 0.3')

    #Threshold
    os.system('main.py --thresh 10')

    #Cropping
    os.system('main.py --set_ROI --ROI_include include')

    #Change frame rate
    os.system('main.py --frameSET --frame_rate 1')

    #Windy conditions
    os.system('main.py --windy --windy_min 1')

    #Burnin by 0.1 minute
    #os.system('main.py --burnin 1')
    ]
    if len(strings) == 1:
        return columns
    # we eliminate all columns that aren't blank for every string
    for s in strings:
        for c in columns[0:]:  # we'll be modifying columns
            if c < len(s) and s[c] != char:
                columns.remove(c)
    columns.sort()
    testtimer.end()
    return columns


if __name__ == '__main__':
    import gourmet.recipeManager as recipeManager
    import tempfile, sys, profile, os.path
    from gourmet.OptionParser import *
    print 'Testing MealMaster import'
    tmpfile = tempfile.mktemp()
    import backends.rmetakit
    rd = backends.rmetakit.RecipeManager(tmpfile)
    if not args: args = ['/home/tom/Projects/recipe/Data/200_Recipes.mmf']
    for a in args:
        profi = os.path.join(tempfile.tempdir, 'MMI_PROFILE')
        profile.run(
            "mmf_importer(rd,a,prog=lambda *args: sys.stdout.write('|'),threaded=False)",
            profi)
        import pstats
        p = pstats.Stats(profi)
        p.strip_dirs().sort_stats('cumulative').print_stats()
import profile


def fib(n):
    if n == 0: return 0
    if n == 1: return 1
    return fib(n - 1) + fib(n - 2)


def fibonacci_seq(n):
    seq = []
    if n > 0:
        seq.extend(fibonacci_seq(n - 1))
    seq.append(fib(n))
    return seq


profile.run('print(fibonacci_seq(20)); print()')

1
Example #49
0
def fib_seq(n):
    seq = []
    if n > 0:
        seq.extend(fib_seq(n - 1))
    seq.append(fib(n))
    return seq


@functools.lru_cache(maxsize=None)
def fib1(n):
    if n == 0:
        return 0
    if n == 1:
        return 1
    return fib1(n - 1) + fib1(n - 2)


def fib_seq1(n):
    seq = []
    if n > 0:
        seq.extend(fib_seq1(n - 1))
    seq.append(fib1(n))
    return seq


if __name__ == "__main__":
    profile.run("print(fib_seq(20))")
    profile.run("print(fib_seq1(20))")
    profile.runctx("print(fib_seq1(n))", globals(), {"n": 20})
Example #50
0
            for query in queries:
                print()
                print(query)
                package = db.get_package(query)
                if not package:
                    print("--- unknown ---")
                    continue
                props = package.get_properties()
                print("Homepages:", props.get_homepages())
                print("Description:", props.description)
                print("License:", props.license)
                print("Slot:", props.get_slot())
                print("Keywords:", props.get_keywords())
                print("USE flags:", props.get_use_flags())
                print("Installed:", package.get_installed())
                print("Latest:", get_version(package.get_latest_ebuild()))
                print(("Latest unmasked:",
                       get_version(package.get_latest_ebuild(0))))

##    main()

    import profile, pstats
    profile.run("main()", "stats.txt")

    stats = pstats.Stats("stats.txt")
    stats.strip_dirs()
    stats.sort_stats('cumulative')
    #stats.sort_stats('time')
    #stats.sort_stats('calls')
    stats.print_stats(0.2)
Example #51
0
def __profile__():
	import profile
	profile.run('__fulltest__()')
import sys, profile

sys.path.append('D:/MyCodes/Python')
from my_math import product

profile.run('product(1,2)')
Example #53
0
def test():
    import profile, pstats
    #profile.run("simple_test()")
    profile.run('stacked_test()', 'barchart.prof')
    p = pstats.Stats('barchart.prof')
    p.sort_stats('cumulative').print_stats(20)
Example #54
0
def oai_profile():
    """
    Runs a benchmark
    """
    from six import StringIO
    oai_list_records_or_identifiers(StringIO(),
                                    argd={
                                        "metadataPrefix": "oai_dc",
                                        "verb": "ListRecords"
                                    })
    oai_list_records_or_identifiers(StringIO(),
                                    argd={
                                        "metadataPrefix": "marcxml",
                                        "verb": "ListRecords"
                                    })
    oai_list_records_or_identifiers(StringIO(),
                                    argd={
                                        "metadataPrefix": "oai_dc",
                                        "verb": "ListIdentifiers"
                                    })
    return


if __name__ == "__main__":
    import profile
    import pstats
    profile.run('oai_profile()', "oai_profile")
    p = pstats.Stats("oai_profile")
    p.strip_dirs().sort_stats("cumulative").print_stats()
    """
    Run count_occurrences_in_text on a few examples
    """
    i = 0
    for x in range(400):
        i += count_occurrences_in_text("word", SAMPLE_TEXT_FOR_BENCH)
        i += count_occurrences_in_text("sugar", SAMPLE_TEXT_FOR_BENCH)
        i += count_occurrences_in_text("help", SAMPLE_TEXT_FOR_BENCH)
        i += count_occurrences_in_text("heavily", SAMPLE_TEXT_FOR_BENCH)
        i += count_occurrences_in_text("witfull", SAMPLE_TEXT_FOR_BENCH)
        i += count_occurrences_in_text("dog", SAMPLE_TEXT_FOR_BENCH)
        i += count_occurrences_in_text("almost", SAMPLE_TEXT_FOR_BENCH)
        i += count_occurrences_in_text("insulin", SAMPLE_TEXT_FOR_BENCH)
        i += count_occurrences_in_text("attaching", SAMPLE_TEXT_FOR_BENCH)
        i += count_occurrences_in_text("asma", SAMPLE_TEXT_FOR_BENCH)
        i += count_occurrences_in_text("neither", SAMPLE_TEXT_FOR_BENCH)
        i += count_occurrences_in_text("won't", SAMPLE_TEXT_FOR_BENCH)
        i += count_occurrences_in_text("green", SAMPLE_TEXT_FOR_BENCH)
        i += count_occurrences_in_text("parabole", SAMPLE_TEXT_FOR_BENCH)
    print(i)


# Start the tests
if __name__ == '__main__':
    # I need to be fast as well:
    import profile
    profile.run('doit()')

    # I need to pass the test:
    unittest.main()
    def __init__(self, sink, baseURI):
        self._sink = sink
        self._baseURI = baseURI

    def feed(self, text):
        p = rdfn3_yapps.Parser(rdfn3_yapps.scanner(text),
                               self._sink, self._baseURI)
        f = getattr(p, 'document')
        f() #raises SyntaxError, etc.


def test(text):
    gen = notation3.ToN3(sys.stdout.write)
    p = Parser(gen, 'http://example.org/2001/stuff/doc23')
    gen.startDoc()
    p.feed(text)
    gen.endDoc()

def testKIF(text, addr):
    import KIFSink
    gen = KIFSink.Sink(sys.stdout.write)
    p = Parser(gen, addr)
    gen.startDoc()
    p.feed(text)
    gen.endDoc()

if __name__ == '__main__':
    import os
    import profile
    profile.run("testKIF(sys.stdin.read(), 'file:%s/STDIN' % (os.getcwd(),))")
Example #57
0
    tishu = 10  #一共十道题
    fenshu = 0
    shurucishu = 1
    while (shurucishu <= 3 and nianji < 1 or nianji > 6):  #小学生是1~6年级
        nianji = int(
            input("您是小学生,请注意,如果输入错误年级次数大于三次你的成绩将为0,你所在的年级是:(n>=1 and n<=6)"))
        shurucishu = shurucishu + 1
    for i in range(1, tishu + 1):
        if (shurucishu > 3):
            break
        if nianji > 3:  #三年级以下题目长度较短
            n = random.randint(3, 10)
        else:
            n = random.randint(2, 4)
        daan = -1
        while (daan < 0):
            daan, ti = timu(nianji, n)
        jieguo = jieguozhuanhuan(input(ti + ""))
        if (jieguo == Fraction(
                '{}'.format(daan)).limit_denominator()):  #判断是否正确
            print("正确")
            fenshu = fenshu + 10
        else:
            print("错误,答案为:", end='')
            print(Fraction('{}'.format(daan)).limit_denominator())
    print("答题结束,总分为" + str(fenshu))  #给出总分


if __name__ == "__main__":
    profile.run('main()')
Example #58
0
    for i in xrange(num_fetch_threads):
        procs.append(Process(name = str(i), target=main2, args=(i, enclosure_queue,)))
        #procs[-1].daemon = True
        procs[-1].start()

    for pth in pth_list:
        enqp(pth)
        

    print '*** Main thread waiting ***'
    enclosure_queue.join()
    print '*** Done ***'

    for p in procs:
        enqp( None )

    enclosure_queue.join()


    for p in procs:
        p.join()

    print "Finished everything...."
    print "num active children:", multiprocessing.active_children()


if __name__=="__main__":
    profile.run("main()")

Example #59
0
                               +sub[9]+'</div></td><td><div class="bsig">'+str(sub[10])+'</div></td></tr>')
                '''
                dlist = sub[15].split('_')
                summary.append('<td>'+time.strftime("%Y/%m/%d %H:%M:%S",time.localtime(sub[16]))+':'+str(int(str(sub[16]).split('.')[1]))+'</td><td>'+sub[0]+'</td><td>'+sub[1]+'</td><td>'+str(sub[2])+'</td><td>'+str(sub[3])+'</td><td>'+str(sub[4])+'</td><td>'\
                               +(dlist[1]+'-'+dlist[3])+'</td><td>'+(dlist[2]+'-'+dlist[4])+'</td><td>'+SC\
                               +'</td><td>'+sub[18]+'</td><td><div class="csig" onmouseover=$(this).children("span.unshow").show() onmouseout=$(this).children("span.unshow").hide()>'\
                               +sub[9]+'</div></td><td><div class="bsig">'+str(sub[10])+'</div></td></tr>')

            summary.append("</tbody>")
    summary.append(
        "</table><script language='JavaScript'>$('#filterName').keyup()</script>"
    )
    #print time.time()
    #print summary
    #pdb.set_trace()
    return ''.join(summary)


if __name__ == '__main__':
    #pdb.set_trace()
    usetime = 100
    pcapNum = 100
    #log=open('log.txt','w')
    files = [
        r'D:\all.pcap',
    ]
    #node,totalflow,valid,invalid,error,L5node=finalNode(files,{},{})
    profile.run("finalNode(files,{},{})")
    #showNode(node,totalflow,valid,invalid,usetime,pcapNum,error,'fp','r')
    #log.close()
Example #60
0
        print "please email the output to the author."
        print "Verbose output automatically enabled"
        options.verbose = 1

    if options.verbose:
        print "Verbose execution enabled"

    if options.stats:
        import pstats
        p = pstats.Stats(options.stats)
        p.sort_stats('cumulative').print_stats(10)
        p.sort_stats('time').print_stats(10)
        sys.exit()

try:
    import psyco
    psyco.full()
except ImportError:
    if options.verbose:
        print "Could not import psyco, ignoring..."

    sf = Soulforge(0)

    if options.profile:
        print "Program execution will be profiled."
        print "Expect it to run a lot slower."
        import profile
        profile.run('sf.MainLoop()', options.profile)
    else:
        sf.MainLoop()