def calibrateprofile():
	pr = profile.Profile()
	calib = []
	crepeat = 10
	for i in range(crepeat):
		calib.append(pr.calibrate(10000))
	final = sum(calib) / crepeat
	profile.Profile.bias = final # Apply computed bias to all Profile instances created hereafter
	return final
예제 #2
0
 def run(self, func, *args, **params):
     """Dump profile data into self.path."""
     global _count
     c = _count = _count + 1
     path = os.path.join(self.path, "cp_%04d.prof" % c)
     prof = profile.Profile()
     result = prof.runcall(func, *args, **params)
     prof.dump_stats(path)
     return result
예제 #3
0
파일: timelog.py 프로젝트: yudaka/viewvc
def profile_stream(stream_class, filename, n=20):
  p = profile.Profile()
  def many_calls(filename, n):
    for i in xrange(n):
      ts = stream_class(open(filename, 'rb'))
      while ts.get() is not None:
        pass
  p.runcall(many_calls, filename, n)
  p.print_stats()
예제 #4
0
파일: foo.py 프로젝트: nolby003/social
def read_file(filename, profile_list):

    # open file containing profiles
    with open(filename, mode="r") as infile:

        # set counter
        index = 0

        # loop through file, begin at first line
        for line in infile:

            # split first line for first name, family name, email and gender
            get_word = line.split()
            # get first object being first name
            given_name = get_word[0]
            # get second object being last name
            family_name = get_word[1]
            # get third object being email
            email = get_word[2]
            # get fourth object being gender
            gender = get_word[3]
            # get next line for status
            line = infile.readline()
            # strip line break after status
            status = str(line.strip('\n'))

            # create new array (using profile class) containing all objects that were set to the variables we needed
            new_profile = profile.Profile(given_name, family_name, email,
                                          gender, status)

            # build profile list from just created array
            # I know list function insert val was required, however this works for PART A, but did not work here ;_(
            #profile_list = list_function.insert_value(profile_list, new_profile, index)
            profile_list.append(new_profile)

            # get next line for number of friends
            line = int(infile.readline())
            # for debugging purposes - count of line
            #print(line)

            # if line is greater than zero, for each friends in range between zero and the total friends, read each line -
            # friends email addresses
            if int(line) > 0:

                for friends in range(0, int(line)):
                    line = infile.readline()
                    friend = line.strip('\n')
                    new_profile.add_friend(friend)

            #increment
            index += 1

    # close file
    infile.close

    return profile_list
예제 #5
0
파일: util.py 프로젝트: seraph0017/twisted
 def _(*args, **kwargs):
     import profile
     prof = profile.Profile()
     try:
         result = prof.runcall(f, *args, **kwargs)
         prof.dump_stats(outputFile)
     except SystemExit:
         pass
     prof.print_stats()
     return result
예제 #6
0
def test_main():
    global ticks
    ticks = 42000
    prof = profile.Profile(timer)
    prof.runctx("testfunc()", globals(), locals())
    assert ticks == 43000, ticks
    st = pstats.Stats(prof)
    st.strip_dirs().sort_stats('stdname').print_stats()
    st.print_callees()
    st.print_callers()
예제 #7
0
def run(cmd):
        prof = profile.Profile()
	try:
		stats = pstats.Stats(prof.run(cmd))
	except SystemExit:
		pass
	stats.strip_dirs().sort_stats("time", "module", "name")
	win = PStatWindow(stats)
	win.show()
	mainloop()
예제 #8
0
 def __call__(self, *args):
     global profiler_stats
     profiler = profile.Profile()
     if profiler_stats is None:
         profiler_stats = pstats.Stats(profiler)
     ps = profiler_stats # thread-etc safe - even if the global goes away under us, this wont!
     ret = profiler.runcall(self.callme, *args)
     if ps is not None:
         ps.add(profiler)
     return ret
예제 #9
0
 def test_random_kmers_are_correct_length(self):
     self.random_profile = profile.Profile('test_data_set_2.txt')
     times = 1000
     while times > 0:
         random_motifs = self.randomized_motif_search._random_k_mers(
             self.random_profile.k, self.random_profile.dna)
         for text in random_motifs:
             self.assertEqual(len(text), 6,
                              'Each random kmer is correct length')
         times -= 1
예제 #10
0
def run_test(outFile, xmlFile, stylesheets):

    tempFileName = tempfile.mktemp()
    p = Processor.Processor()
    prof = profile.Profile()

    prof.runctx("profile_test(p,xmlFile,stylesheets)", globals(), locals())
    prof.dump_stats(tempFileName)

    return tempFileName
예제 #11
0
        def func_wrapper(self, module, input):

            try:
                event = input['event']
                # *** Filter indirect events out (like for groups related to the configured item)
                if getattr(event, "getItemName",
                           None) is not None and event.getItemName(
                           ) not in self.triggerItems:
                    self.log.debug("Rule skipped. Event is not related" +
                                   appendDetailInfo(self, event))
                    return
            except KeyError:
                event = None

            try:
                start_time = time.clock()

                # *** execute
                if proxy.profile:
                    pr = profile.Profile()

                    #self.log.debug(str(getItem("Lights")))
                    #pr.enable()
                    pr.runctx(
                        'func(self, module, input)', {
                            'self': self,
                            'module': module,
                            'input': input,
                            'func': func
                        }, {})
                    status = None
                else:
                    status = func(self, module, input)

                if proxy.profile:
                    #pr.disable()
                    s = io.BytesIO()
                    #http://www.jython.org/docs/library/profile.html#the-stats-class
                    ps = pstats.Stats(pr, stream=s).sort_stats('cumulative')
                    ps.print_stats()
                    self.log.debug(s.getvalue())

                if status is None or status is True:
                    elapsed_time = round((time.clock() - start_time) * 1000, 1)

                    msg = "Rule executed in " + "{:6.1f}".format(
                        elapsed_time) + " ms" + appendDetailInfo(self, event)

                    self.log.debug(msg)

            except NotInitialisedException as e:
                self.log.warn("Rule skipped: " + str(e))
            except:
                self.log.error("Rule execution failed:\n" +
                               traceback.format_exc())
예제 #12
0
def publish_module_profiled(module_name,
                            stdin=sys.stdin,
                            stdout=sys.stdout,
                            stderr=sys.stderr,
                            environ=os.environ,
                            debug=0,
                            request=None,
                            response=None):
    import profile, pstats
    global _pstat
    _plock.acquire()
    try:
        if request is not None:
            path_info = request.get('PATH_INFO')
        else:
            path_info = environ.get('PATH_INFO')
        if path_info[-14:] == 'manage_profile':
            return _pfunc(module_name,
                          stdin=stdin,
                          stdout=stdout,
                          stderr=stderr,
                          environ=environ,
                          debug=debug,
                          request=request,
                          response=response)
        pobj = profile.Profile()
        pobj.runcall(pm, module_name, stdin, stdout, stderr, environ, debug,
                     request, response)
        result = sys._pr_
        pobj.create_stats()
        if _pstat is None:
            _pstat = sys._ps_ = pstats.Stats(pobj)
        else:
            _pstat.add(pobj)
    finally:
        _plock.release()

    if result is None:
        try:
            error = sys.exc_info()
            file = open(_pfile, 'w')
            file.write(
                "See the url "
                "http://www.python.org/doc/current/lib/module-profile.html"
                "\n for information on interpreting profiler statistics.\n\n")
            sys.stdout = file
            _pstat.strip_dirs().sort_stats('cumulative').print_stats(250)
            _pstat.strip_dirs().sort_stats('time').print_stats(250)
            file.flush()
            file.close()
        except:
            pass
        raise error[0], error[1], error[2]
    return result
예제 #13
0
def main():
    parse_cmdline(sys.argv[1:])
    if not PROFILE:
        gamesrv.mainloop()
    else:
        import profile
        prof = profile.Profile()
        try:
            prof = prof.run('gamesrv.mainloop()')
        finally:
            prof.dump_stats('profbb')
예제 #14
0
def data_prep(seed):
    profile = profile.Profile()
    interest = interest.Interest()
    preprocess = preprocess.Preprocessor()
    profile_raw = profile.get_profile()
    interest_raw, ids = interest.data_merge()
    data = preprocess.finalize_data(profile_raw, interest_raw)
    X, y, X_train, y_train, X_test, y_test = preprocess.split_data(data,
                                                                   seed=seed,
                                                                   re=False)
    return X, y, X_train, y_train, X_test, y_test, ids
예제 #15
0
 def run_it_with_profiling():
     import profile
     p = profile.Profile()
     p.runcall(app.start)
     import tempfile
     (
         tmpfile,
         tmpfname,
     ) = tempfile.mkstemp(prefix='shtoomphone')
     p.dump_stats(tmpfname)
     del p
예제 #16
0
def getProfileListFromFile():
    import profile # get latest
    profileList = []
    with open(profilePath) as data_file:
        js = json.load(data_file)
    l = js["profile"]
    ######
    for item in l:
        p = profile.Profile(item["name"], item["startDateTime"], item["interval"], item["period"])
        profileList.append(p)

    return profileList
예제 #17
0
 def profile(self, filename):
     p = profile.Profile()
     com = 'execfile("%s")' % filename
     p.run(com)
     p.snapshot_stats()
     outf = tempfile.mktemp('pida-profile')
     f = open(outf, 'w')
     s = pickle.dump(p.stats, f)
     f.close()
     self.ipc.write('stats', outf, 8)
     while gtk.events_pending():
         gtk.main_iteration()
예제 #18
0
    def test_profile_module(self):
        def test(a, b):
            return a * b

        a, b = (2, 3)
        prof = profile.Profile()
        ret = prof.runcall(test, a, b)
        prof.print_stats()
        self.assertIsInstance(ret, int)
        self.assertEqual(ret, 6)
        self.assertRegexpMatches(sys.stdout.getvalue(),
                                 r'3 function calls in [0-9\.]+ seconds')
def greedy_motif_search(dna, k, t):
    first_motifs = first_kmers(dna, k)
    best_profile = profile.Profile(None, k, first_motifs, 1)
    best_score = [best_profile.motif_score(), first_motifs]
    for i in range(0,len(dna[0])-k+1):
        motifs = [dna[0][i:i+k]]
        motif_profile = profile.Profile(None, k, motifs, 1)
        for j in range(1,len(dna)):
            most_probable_kmers = most_probable(motif_profile, [dna[j]])
            for motif in most_probable_kmers:
                if motif is not None:
                    motifs.extend([motif])
                else:
                    motifs.extend([first_motifs[j]])
            motif_profile = profile.Profile(None, k, motifs, 1)
            resulting_kmers = [dna[j], most_probable_kmers, motif_profile.motif_score()]
        motif_profile = profile.Profile(None, k, motifs, 1)
        current_score = motif_profile.motif_score()
        if current_score < best_score[0]:
            best_score = [current_score, motifs]
    return best_score[1]
예제 #20
0
def profile(fn, *args):
    import profile
    prof = profile.Profile()
    try:
        # roll on 1.6 :-)
        #		return prof.runcall(fn, *args)
        return prof.runcall(*(fn, ) + args)
    finally:
        import pstats
        # Damn - really want to send this to Excel!
        #      width, list = pstats.Stats(prof).strip_dirs().get_print_list([])
        pstats.Stats(prof).strip_dirs().sort_stats("time").print_stats()
예제 #21
0
def calibrateprofile():
    '''
    Calibrate the profiler (necessary to have non negative and more exact values)
    '''
    pr = profile.Profile()
    calib = []
    crepeat = 10
    for i in range(crepeat):
        calib.append(pr.calibrate(10000))
    final = sum(calib) / crepeat
    profile.Profile.bias = final  # Apply computed bias to all Profile instances created hereafter
    return final
예제 #22
0
파일: Test.py 프로젝트: bendavis78/zope
def run(statement, *args):
    import sys, profile, time

    prof = profile.Profile(time.time)
    try:
        prof = prof.run(statement)
    except SystemExit:
        pass
    if args:
        prof.dump_stats(args[0])
    else:
        return prof.print_stats()
예제 #23
0
def doProfile(httpd, howmany):
    #h = hotshot.Profile("dwikin.prof")
    #h.runcall(runLimited, (httpd, howmany))
    #h.close()
    #stats = hotshot.stats.load("dwikin.prof")
    p = profile.Profile()
    p.runcall(runLimited, httpd, howmany)
    stats = pstats.Stats(p)

    stats.strip_dirs()
    stats.sort_stats("time", "calls")
    stats.print_stats(40)
예제 #24
0
 def wrapper(*args, **kwargs):
     import profile
     res = ObjectStateHolderVector()
     prof = profile.Profile()
     try:
         res = prof.runcall(main_fn, *args, **kwargs)
     except SystemExit:
         pass
     if filename is not None:
         prof.dump_stats(filename)
     else:
         prof.print_stats(sort)
     return res
예제 #25
0
def profile_main(n=18):
    import profile, pstats
    print "Running under profiler...."
    profiler = profile.Profile()
    try:
        profiler.runctx('main()', globals(), locals())
    finally:
        sys.stdout = logfile
        profiler.dump_stats('@html2ps.prof')
        p = pstats.Stats('@html2ps.prof')
        p.strip_dirs().sort_stats('time').print_stats(n)
        p.print_callers(n)
        p.sort_stats('cum').print_stats(n)
예제 #26
0
 def test_bioinformatics_book_p92(self):
     alt_file = 'fixtures/bioinformatics_book_p92.txt'
     self.alt_profile = profile.Profile(alt_file)
     dna_strings = [
         "TTACCTTAAC", "GATGTCTGTC", "ACGGCGTTAG", 'CCCTAACGAG',
         "CGTCAGAGGT"
     ]
     self.assertEqual(
         ' '.join(
             self.randomized_motif_search.most_probable(
                 self.alt_profile,
                 dna_strings)), "ACCT ATGT GCGT ACGA AGGT",
         'Computes most probable k-mer pattern in dna')
예제 #27
0
def add_profile(profile_list):
    email = input('Please enter email address: ')
    if find_profile(profile_list, email) > -1:
        print(f'<{email}> already exists in profiles.')
    else:
        g_name = input('Please enter given name: ')
        f_name = input('Please enter family name: ')
        gender = input('Please enter gender: ')
        status = input('Please enter current status: ')
        profile_ = profile.Profile(g_name, f_name, email, gender, status)
        profile_list.append(profile_)
        print(f'Successfully added <{email}> to profiles.')
    return profile_list
예제 #28
0
def read_file(filename, profile_list):
    with open(filename) as f:
        for line in f:
            friends = []  # friends list of each profile read from a file
            person = line.split()
            status = f.readline().strip('\n')
            friend_num = int(f.readline())
            for _ in range(friend_num):
                friends.append(f.readline().strip('\n'))
            profile_ = profile.Profile(person[0], person[1], person[2],
                                       person[3], status)
            profile_.set_friends_list(friends)
            profile_list.append(profile_)
    return profile_list
 def setUp(self):
     super(QueryWithStatsTest, self).setUp()
     self.useFixture(fixtures.FakeLogger())
     self.db = db.DB(':memory:')
     self.db.start_run(
         '12345',
         '/no/such/dir',
         ['command', 'line', 'would', 'go', 'here'],
         1370436103.65,
     )
     self.local_values = {'name': ['value', 'pairs']}
     self.trace_arg = [{'complex': 'value'}]
     self.db.trace(
         run_id='12345',
         thread_id='t1',
         call_id='abcd',
         event='test',
         func_name='test_trace',
         line_no=99,
         filename='test_db.py',
         trace_arg=self.trace_arg,
         local_vars=self.local_values,
         timestamp=1370436104.65,
     )
     self.db.trace(
         run_id='12345',
         thread_id='t1',
         call_id='abcd',
         event='test',
         func_name='test_trace',
         line_no=100,
         filename='test_db.py',
         trace_arg=self.trace_arg,
         local_vars=self.local_values,
         timestamp=1370436104.65,
     )
     self.db.start_run(
         '6789',
         '/no/such/dir',
         ['command', 'line', 'would', 'go', 'here'],
         1370436104.65,
     )
     stats_data = stats.stats_to_blob(pstats.Stats(profile.Profile()))
     self.db.end_run(
         '6789',
         1370436105.65,
         'error message',
         None,
         stats=stats_data,
     )
예제 #30
0
def make_hole(diameter, length):
    pos = [0.0]
    diam = [diameter]

    radius = diameter * 0.5
    n = 4
    for i in range(0, n):
        x = math.pi / 2 * float(i) / n
        pos.append(length + radius * (math.sin(x) - 1))
        diam.append(diameter * math.cos(x))

    prof = profile.Profile(pos, diam, diam)
    hole = shape.extrude_profile(prof)

    return hole