コード例 #1
0
ファイル: parse_pcap.py プロジェクト: rouge8/pig
 def handle(self, *args, **options):
     if options['profile']:
         profiler = Profile()
         profiler.runcall(self._handle, *args, **options)
         profiler.print_stats()
     else:
         self._handle(*args, **options)
コード例 #2
0
    def handle(self, **options):
        """Django entry point."""
        def validate_options():
            """Validate command line options."""
            if not options['destination']:
                raise CommandError('Please specify the --destination option')

            if not options['format']:
                raise CommandError('Please specify the --format option')

            if options['format'] in ['bed', 'all'] and not options['bedToBigBed']:
                raise CommandError('Please specify the --bedToBigBed option')

            if options['format'] not in self.formats:
                raise CommandError('Please choose a valid output format (%s)' % '|'.join(self.formats))

        validate_options()

        if options['profile']:
            profiler = Profile()
            profiler.runcall(self.export, **options)
            profiler.print_stats()
            profiler.dump_stats('profile.txt')
        elif options['format'] == 'all':
            self.export_all(**options)
        else:
            self.export(**options)
コード例 #3
0
    def handle(self, *args, **options):
        """
        Main function, called by django.
        """

        if options['upis']:
            options['upis'] = options['upis'].split(',')
        elif options['upi_file']:
            with open(options['upi_file'], 'rb') as raw:
                options['upis'] = [line.strip() for line in raw]
        else:
            if not options['min'] and options['min'] != 0:
                raise CommandError('Please specify --min')

            if not options['max']:
                raise CommandError('Please specify --max')

            options['min'] = int(options['min'])
            options['max'] = int(options['max'])

        if not options['date']:
            options['date'] = date.today()
        else:
            options['date'] = dt.strptime(options['date'], '%Y-%m-%d')

        if options['profile']:
            profiler = Profile()
            profiler.runcall(self.run, options)
            profiler.print_stats()
            profiler.dump_stats('profile.txt')
        else:
            self.run(options)
コード例 #4
0
ファイル: test_disjoint_set.py プロジェクト: Tsumida/dsalgo
    def test_perf(self):
        def test_union(ds: DisjointSet, random_seq):
            for a, b in random_seq:
                ds.union(a, b)

        n = 64000
        random_key = list(set(randint(0, n) for _ in range(n)))
        n = len(random_key)
        random_tup = [(choice(random_key), choice(random_key))
                      for _ in range(n << 1)]
        ds = DisjointSet(random_key)
        print("-" * 32)

        p2 = Profile()
        p2.runcall(test_union, ds=ds, random_seq=random_tup)
        p2.print_stats()
        print("-" * 32, "n = ", n)

        levels = ds.get_levels()
        for c, num in levels:
            print("level = {}, num = {:8}, per = {}".format(
                c, num, round(num / n, 4)))

        print("Expected level: ",
              round(sum(c * num / n for c, num in levels), 4))
コード例 #5
0
def profile(sort):
    if not sort:
        yield
        return
    sort_columns = (
        "calls",
        "cumtime",
        "file",
        "ncalls",
        "pcalls",
        "line",
        "name",
        "nfl",
        "stdname",
        "time",
        "tottime",
    )
    if sort not in sort_columns:
        raise RuntimeError(
            "{} not a valid sort column. Please use one of {}".format(
                sort, ", ".join(sort_columns)))
    try:
        from cProfile import Profile  # type: ignore
    except ImportError:
        from Profile import Profile  # type: ignore
    prof = Profile()
    prof.enable()
    yield
    prof.create_stats()
    prof.print_stats(sort=sort)
コード例 #6
0
    def handle(self, **options):
        """
        Django entry point.
        """
        def validate_options():
            """
            Validate command line options.
            """
            if not options['destination']:
                raise CommandError('Please specify the --destination option')

            if not options['format']:
                raise CommandError('Please specify the --format option')

            if options['format'] in ['bed', 'all'] and not options['bedToBigBed']:
                raise CommandError('Please specify the --bedToBigBed option')

            if options['format'] not in self.formats:
                raise CommandError('Please choose a valid output format (%s)' % '|'.join(self.formats))

        validate_options()

        if options['profile']:
            profiler = Profile()
            profiler.runcall(self.export, **options)
            profiler.print_stats()
            profiler.dump_stats('profile.txt')            
        elif options['format'] == 'all':
            self.export_all(**options)
        else:
            self.export(**options)
コード例 #7
0
 def wrap(*args, **kw):
     pr = Profile()
     pr.enable()
     result = func(*args, **kw)
     pr.disable()
     pr.print_stats()
     return result
コード例 #8
0
 def handle(self, *args, **options):
     if options['profile']:
         profiler = Profile()
         profiler.runcall(self._handle, *args, **options)
         profiler.print_stats()
     else:
         self._handle(*args, **options)
コード例 #9
0
 def run(self):
   haichi=[[0 for i in range(8)] for j in range(15)]
   for i in range(15):
     haichi[i][0]=20
     haichi[i][7]=20
   for i in range(1,7):
     haichi[0][i]=20
   fort=Fort()
   ai=aiclass.AIField(haichi)
   t1=time.time()
   pr=Profile()
   pr.enable()
   for i in range(1000):
     ai.haichi[1][1]=i%4
     ai.haichi[1][2]=i%3
     ai.haichi[1][3]=i%2
     ai.haichi[1][4]=i%3
     ai.haichi[1][5]=4
     ai.haichi[1][6]=1
     ai.haichi[2][1]=1
     ai.haichi[2][2]=1
     ai.haichi[2][3]=3
     ai.haichi[2][4]=2
     ai.haichi[2][5]=3
     
     fort.call_fortran(ai.haichi)
   pr.disable()
   pr.print_stats()
   t2=time.time()
   print(t2-t1)
   print(haichi)
コード例 #10
0
ファイル: __init__.py プロジェクト: rkorytkowski/oclapi
 def handle(self, *args, **options):
     """ Handles the command line arguments - initiates profiling if set to true """
     if options.get('profile', False):
         profiler = Profile()
         profiler.runcall(self._handle, *args, **options)
         profiler.print_stats()
     else:
         self._handle(*args, **options)
コード例 #11
0
 def handle(self, *args, **options):
     """ Handles the command line arguments - initiates profiling if set to true """
     if options.get('profile', False):
         profiler = Profile()
         profiler.runcall(self._handle, *args, **options)
         profiler.print_stats()
     else:
         self._handle(*args, **options)
コード例 #12
0
 def handle(self, *args, **options):
     # run with profiling
     if options['profile']:
         profiler = Profile()
         profiler.runcall(self._handle, *args, **options)
         profiler.print_stats()
     # run without profiling
     else:
         self._handle(*args, **options)
コード例 #13
0
    def handle(self, *args, **options):
        """Command entrypoint"""

        if options['profile']:
            profiler = Profile()
            profiler.runcall(self._handle, *args, **options)
            profiler.print_stats()
        else:
            self._handle(*args, **options)
コード例 #14
0
 def handle(self, *args, **options):
     # run with profiling
     if options['profile']:
         profiler = Profile()
         profiler.runcall(self._handle, *args, **options)
         profiler.print_stats()
     # run without profiling
     else:
         self._handle(*args, **options)
コード例 #15
0
ファイル: profile_tools.py プロジェクト: jiaxu825/SUAVE
 def profiled_func(*args, **kwargs):
     p = Profile()
     try:
         # profile the input function
         p.enable()
         r = f(*args, **kwargs)
         p.disable()
         return r
     finally:
         p.print_stats()
コード例 #16
0
def apply_some_filters_profile():
    frames = tests.input_bulk(200)

    profiler = Profile()
    profiler.enable()

    augmentation.apply_some_filters(frames, tests.config.framerate)

    profiler.disable()
    profiler.print_stats()
コード例 #17
0
 def wrapper(*args, **kwargs):
     profiler = Profile()
     result = profiler.runcall(func, *args, **kwargs)
     if print_data:
         profiler.print_stats()
     filename = func.__name__
     profiler.dump_stats(filename)
     if visualized:
         visualize(filename, host, port)
     return result
コード例 #18
0
def main():
    prof = Profile()
    prof.runcall(test_1)
    prof.print_stats()

    print("-" * 20)

    prof2 = Profile()
    prof2.runcall(test_2)
    prof2.print_stats()
コード例 #19
0
ファイル: decorations.py プロジェクト: saetar/pyEuler
 def profiled_funk(*args, **kwargs):
     profile = Profile()
     try:
         profile.enable()
         ret_val = funk(*args, **kwargs)
         profile.disable()
     finally:
         print("__CPROFILE__")
         profile.print_stats()
     return ret_val
コード例 #20
0
    def profiled_funk(*args, **kwargs):
        """wrapper funk"""

        profile = Profile()
        try:
            profile.enable()
            ret_val = funk(*args, **kwargs)
            profile.disable()
        finally:
            print("__CPROFILE__")
            profile.print_stats("cumulative")
        return ret_val
コード例 #21
0
ファイル: ftp_export.py プロジェクト: lmmx/rnacentral-webcode
    def handle(self, *args, **options):
        """
        Main function, called by django.
        """
        def _handle(self, *args, **options):
            """
            Main program. Separated from `handle` to enable Python profiling.
            """
            def set_command_line_options():
                """
                Store the command line options in the corresponding `self` variables.
                """
                cmd_options = ['bedToBigBed', 'destination', 'format', 'test']
                for cmd_option in cmd_options:
                    if options[cmd_option]:
                        self.options[cmd_option] = options[cmd_option]

            def validate_command_line_options():
                """
                Validate the command line options.
                """
                if not self.options['destination']:
                    raise CommandError(
                        'Please specify the --destination option')
                if not os.path.exists(self.options['destination']):
                    os.makedirs(self.options['destination'])
                if not self.options['bedToBigBed'] and (
                        options['format'] == 'bed'
                        or options['format'] == 'all'):
                    raise CommandError(
                        'Please specify the --bedToBigBed option')
                if not self.options['format']:
                    raise CommandError('Please specify the --format option')
                if self.options['format'] not in self.formats:
                    raise CommandError(
                        'Please specify correct output format. See --help for details.'
                    )

            set_command_line_options()
            validate_command_line_options()
            self.export_factory(mode=self.options['format'])

        if options['profile']:
            profiler = Profile()
            profiler.runcall(_handle, self, *args, **options)
            profiler.print_stats()
        else:
            _handle(self, *args, **options)
コード例 #22
0
ファイル: main.py プロジェクト: JayTSmith/scraps
def prof_main():
    from cProfile import Profile

    prof = Profile()
    prof.enable()
    fish = factory.run_silent_game(player_count=6)
    prof.disable()

    line_sep_char = '#'

    win_string = '{1} Winners: {0}'.format(
        ', '.join(['Player ' + p.name for p in fish.winner]), line_sep_char)
    sep = line_sep_char * len(win_string)
    print('\n{0}\n{1}\n{0}'.format(sep, win_string))

    prof.print_stats()
    return fish
コード例 #23
0
ファイル: main.py プロジェクト: EthanEdwardDall/go-fish
def prof_main():
    from cProfile import Profile

    prof = Profile()
    prof.enable()
    fish = BasicGoFish(build_players())
    fish.do_full_round()
    prof.disable()

    line_sep_char = '#'

    win_string = '{1} Winners: {0}'.format(
        ', '.join(['Player ' + p.name for p in fish.winner]), line_sep_char)
    sep = line_sep_char * len(win_string)
    print('\n{0}\n{1}\n{0}'.format(sep, win_string))

    prof.print_stats()
    return fish
コード例 #24
0
    def handle(self, *args, **options):
        """
        Main function, called by django.
        """

        def _handle(self, *args, **options):
            """
            Main program. Separated from `handle` to enable Python profiling.
            """

            def set_command_line_options():
                """
                Store command line options in `self.options`.
                """
                cmd_options = ["destination", "min", "max"]
                for cmd_option in cmd_options:
                    if options[cmd_option]:
                        self.options[cmd_option] = str(options[cmd_option])

            def validate_command_line_options():
                """
                Validate the command line options.
                """
                if not self.options["destination"]:
                    raise CommandError("Please specify --destination")
                if not self.options["min"]:
                    raise CommandError("Please specify --min")
                if not self.options["max"]:
                    raise CommandError("Please specify --max")
                if not os.path.exists(self.options["destination"]):
                    os.makedirs(self.options["destination"])

            set_command_line_options()
            validate_command_line_options()
            self.export_data()

        if options["profile"]:
            profiler = Profile()
            profiler.runcall(_handle, self, *args, **options)
            profiler.print_stats()
            profiler.dump_stats("profile.txt")
        else:
            _handle(self, *args, **options)
コード例 #25
0
ファイル: ftp_export.py プロジェクト: lmmx/rnacentral-webcode
    def handle(self, *args, **options):
        """
        Main function, called by django.
        """
        def _handle(self, *args, **options):
            """
            Main program. Separated from `handle` to enable Python profiling.
            """
            def set_command_line_options():
                """
                Store the command line options in the corresponding `self` variables.
                """
                cmd_options = ['bedToBigBed', 'destination', 'format', 'test']
                for cmd_option in cmd_options:
                    if options[cmd_option]:
                        self.options[cmd_option] = options[cmd_option]

            def validate_command_line_options():
                """
                Validate the command line options.
                """
                if not self.options['destination']:
                    raise CommandError('Please specify the --destination option')
                if not os.path.exists(self.options['destination']):
                    os.makedirs(self.options['destination'])
                if not self.options['bedToBigBed'] and (options['format'] == 'bed' or options['format'] == 'all'):
                    raise CommandError('Please specify the --bedToBigBed option')
                if not self.options['format']:
                    raise CommandError('Please specify the --format option')
                if self.options['format'] not in self.formats:
                    raise CommandError('Please specify correct output format. See --help for details.')

            set_command_line_options()
            validate_command_line_options()
            self.export_factory(mode=self.options['format'])

        if options['profile']:
            profiler = Profile()
            profiler.runcall(_handle, self, *args, **options)
            profiler.print_stats()
        else:
            _handle(self, *args, **options)
コード例 #26
0
ファイル: xml_export.py プロジェクト: lmmx/rnacentral-webcode
    def handle(self, *args, **options):
        """
        Main function, called by django.
        """
        def _handle(self, *args, **options):
            """
            Main program. Separated from `handle` to enable Python profiling.
            """
            def set_command_line_options():
                """
                Store command line options in `self.options`.
                """
                cmd_options = ['destination', 'min', 'max']
                for cmd_option in cmd_options:
                    if options[cmd_option]:
                        self.options[cmd_option] = str(options[cmd_option])

            def validate_command_line_options():
                """
                Validate the command line options.
                """
                if not self.options['destination']:
                    raise CommandError('Please specify --destination')
                if not self.options['min']:
                    raise CommandError('Please specify --minimum')
                if not self.options['max']:
                    raise CommandError('Please specify --maximum')
                if not os.path.exists(self.options['destination']):
                    os.makedirs(self.options['destination'])

            set_command_line_options()
            validate_command_line_options()
            self.export_data()

        if options['profile']:
            profiler = Profile()
            profiler.runcall(_handle, self, *args, **options)
            profiler.print_stats()
            profiler.dump_stats('profile.txt')
        else:
            _handle(self, *args, **options)
コード例 #27
0
    def handle(self, *args, **options):
        global verbose
        log = options['log']
        year = options['year']
        verbose = options['verbose']
        if log:
            with open('elo.tsv', 'w', encoding='utf-8') as file:
                elo_leaders = TeamLeaderboard.highest_elo_scaled()
                row_fmt = "%s\t%s\t%s\t%s"
                file.writelines([
                                    (row_fmt % (
                                        rank, str(team).replace("\t", ""), team.elo_scaled, team.elo_sigma)).replace(
                                        '"',
                                        "''")
                                    for rank, team in enumerate(elo_leaders, start=1)
                                    ])
                # Replace double quotes so we can post it to Gist without Github freaking out
                # Replace tab characters because Team 422 has a tab in their name (WHY?!)
                # More teams have commas than tabs in their names so just uses .tsv file
        elif options['event'] == '':
            time_start = clock()
            if year == 0:
                for yr in SUPPORTED_YEARS[:-1]:
                    add_all_elo(yr)
                    soft_reset(yr)

                add_all_elo(SUPPORTED_YEARS[-1])
            else:
                add_all_elo(year)
            time_end = clock()
            print("-------------")
            print("Matches added:\t\t{0}".format(matches_added))
            print("Ran in {0} seconds.".format(round(time_end - time_start, 3)))
            print("-------------")
        else:
            # add_event_elo(Event.objects.get(key=options['event']))
            from cProfile import Profile
            profiler = Profile()
            profiler.runcall(add_event_elo, Event.objects.get(key=options['event']))
            profiler.print_stats(2)
コード例 #28
0
 def profiled_func(*args, **kwargs):
     profile = Profile()
     result = None
     try:
         profile.enable()
         result = func(*args, **kwargs)
         profile.disable()
     except catch_exception as exc:
         result = exc
     finally:
         write_dir = profile_dir.format(cwd=getcwd())
         if write_profile and path.isdir(write_dir):
             write_name = "{}.prof".format(
                 profile_name.format(
                     funcname=func.__name__, pid=getpid(),
                     timestamp=datetime.now().strftime("%Y%m%d_%H%M%S")
                 ))
             profile_path = path.join(write_dir, write_name)
             profile.dump_stats(profile_path)
         else:
             profile.print_stats()
     return result
コード例 #29
0
    def handle(self, *args, **options):
        """
        Main function, called by django.
        """
        def _handle(self, *args, **options):
            """
            Main program. Separated from `handle` to enable Python profiling.
            """
            def set_command_line_options():
                """
                Store command line options in `self.options`.
                """
                cmd_options = ['min', 'max']
                for cmd_option in cmd_options:
                    if options[cmd_option]:
                        self.options[cmd_option] = str(options[cmd_option])

            def validate_command_line_options():
                """
                Validate the command line options.
                """
                if not self.options['min']:
                    raise CommandError('Please specify --min')
                if not self.options['max']:
                    raise CommandError('Please specify --max')

            set_command_line_options()
            validate_command_line_options()
            self.run()

        if options['profile']:
            profiler = Profile()
            profiler.runcall(_handle, self, *args, **options)
            profiler.print_stats()
            profiler.dump_stats('profile.txt')
        else:
            _handle(self, *args, **options)
コード例 #30
0
        return _

    funcs = {}
    funcs['sin'] = noisy_mapping(np.sin)
    funcs['log'] = noisy_mapping(np.log)
    funcs['pow1.5'] = noisy_mapping(lambda x: x**(3 / 2))

    X = np.arange(0.1, 10, step=0.001)

    import pennpaper as pp
    from collections import defaultdict

    metrics = defaultdict(list)

    for i in range(90):
        for name, f in funcs.items():
            m = pp.Metric(name)
            m.add_arrays(X, f(X))
            metrics[m.name].append(m)

    metrics = [sum(v) for v in metrics.values()]

    pp.plot_group(metrics)
    pp.plot_group(metrics, smoothen=True)


from cProfile import Profile
p = Profile()
p.runcall(measure)
p.print_stats('cumulative')
コード例 #31
0
    assert is_sorted(numbers)

def test_quick():
    numbers = [randint(0, 10000) for i in range(max_num)]
    quick_sort(numbers, 0, max_num-1)
    i = 1
    while i < max_num:
        assert numbers[i] >= numbers[i-1]
        i += 1

def test_all():
    numbers = [randint(0, 10000) for i in range(max_num)]
    numbers_m = DoubleLinkedList()
    numbers_b = DoubleLinkedList()
    for i in numbers:
        numbers_m.shift(i)
        numbers_b.shift(i)
    quick_sort(numbers, 0, max_num-1)
    merge_sort(numbers_m)
    bubble_sort(numbers_b)


if __name__ == '__main__':
    prof = Profile()
    prof.enable()
    test_all()
    prof.create_stats()
    prof.print_stats('sorting.py', sort="cumulative")


    
コード例 #32
0
ファイル: 447.py プロジェクト: Tsumida/dsalgo
def test_profile():
    s = Solution()
    assert 0 == s.numberOfBoomerangs(points=[])
    assert 2 == s.numberOfBoomerangs(points=[[0, 0], [1, 0], [2, 0]])
    points = [[489, 238], [323, 460], [853, 965], [327, 426], [264, 871],
              [580, 947], [362, 275], [241, 772], [967, 240], [68, 847],
              [825, 703], [922, 898], [769, 217], [23, 160], [472, 802],
              [755, 313], [40, 78], [125, 246], [396, 452], [672, 660],
              [323, 253], [607, 37], [880, 201], [161, 847], [441, 229],
              [46, 266], [284, 320], [516, 53], [889, 539], [565, 713],
              [341, 320], [26, 381], [751, 504], [979, 147], [956, 652],
              [807, 632], [257, 767], [669, 489], [968, 831], [336, 409],
              [60, 734], [27, 697], [54, 543], [750, 944],
              [82, 668], [657, 423], [988, 36], [156, 91], [540, 136],
              [238, 496], [140, 398], [128, 397], [165, 150], [238, 133],
              [981, 926], [894, 393], [660, 921], [90, 66], [464, 193],
              [10, 898], [861, 20], [321, 201], [408, 829], [293, 948],
              [965, 531], [796, 457], [929, 277], [206, 446], [427, 444],
              [931, 760], [370, 825], [153, 30], [98, 244], [449, 914],
              [789, 811], [812, 650], [831, 485], [203, 239], [315, 496],
              [539, 632], [380, 336], [442, 661], [613, 648], [108, 392],
              [93, 391], [152, 815], [217, 305], [198, 667], [901, 647],
              [934, 690], [458, 746], [692, 642], [584, 896], [233, 251],
              [744, 773], [235, 124], [109, 677], [786, 74], [326, 246],
              [466, 771], [989, 618], [586, 558], [923, 136], [226, 177],
              [783, 160], [867, 594], [258, 912], [236, 842], [808, 469],
              [445, 552], [242, 681], [29, 703], [358, 167], [777, 36],
              [765, 595], [807, 754], [213, 746], [313, 489], [882, 539],
              [666, 18], [51, 885], [612, 309], [149, 200], [504, 957],
              [669, 949], [862, 264], [630, 891], [319, 341], [410, 449],
              [377, 175], [44, 537], [929, 610], [635, 242], [99, 869],
              [133, 117], [887, 184], [354, 851], [846, 504], [51, 350],
              [813, 73], [651, 675], [337, 634], [918, 656], [975, 328],
              [105, 704], [503, 502], [241, 785], [112, 876], [27, 211],
              [98, 513], [680, 985], [697, 386], [189, 895], [890, 240],
              [245, 56], [313, 897], [83, 2], [531, 2], [659, 858], [682, 116],
              [562, 538], [618, 804], [323, 730], [32, 702], [293, 482],
              [215, 325], [468, 265], [64, 657], [160, 306], [249, 406],
              [362, 915], [655, 446], [917, 538], [800, 576], [396, 482],
              [45, 310], [20, 15],
              [466, 343], [98, 851], [46, 743], [333, 261], [421, 801],
              [878, 485], [810, 39], [791, 412], [797, 154], [327, 452],
              [600, 244], [342, 400], [173, 90], [234, 570], [400, 255],
              [585, 867], [950, 683], [718, 996], [779, 51], [610, 200],
              [205, 488], [685, 367], [879, 476], [779, 676], [982, 458],
              [128, 934], [703, 822], [686, 228], [912, 921], [798, 313],
              [176, 735], [180, 478], [771, 898], [475, 550], [301, 437],
              [750, 506], [277, 787], [226, 157], [615, 5], [833, 598],
              [816, 314], [532, 519], [136, 219], [99, 49], [492, 249],
              [362, 20], [984, 894], [498, 755], [144, 325], [657, 445],
              [762, 407], [304, 392], [546, 530], [549, 162], [887, 734],
              [760, 703], [48, 644], [574, 537], [215, 673], [938, 707],
              [922, 652], [727, 259], [546, 226], [14, 42], [551, 24],
              [487, 666], [783, 143], [58, 330], [673, 959], [492, 913],
              [693, 604], [616, 94], [248, 191], [631, 816], [216, 569],
              [523, 491], [573, 603], [750, 119], [181, 116], [513, 84],
              [140, 0], [750, 924], [496, 160], [254, 521], [119, 98],
              [434, 165], [702, 51], [259, 302], [594, 242], [118, 810],
              [163, 994], [653, 736], [597, 403], [207, 778], [520, 720],
              [862, 12], [72, 965], [936, 568], [125, 542], [442, 597],
              [640, 876], [762, 694], [279, 373], [997, 225], [967, 467],
              [388, 130], [461, 41], [218, 410], [445, 425], [540, 317],
              [497, 403], [329, 569], [720, 266], [490, 197], [808, 932],
              [146, 801], [160, 260], [495, 440], [633, 844], [17, 600],
              [312, 405], [82, 125], [447, 300], [536, 244], [77, 76],
              [561, 574], [831, 890], [144, 903], [508, 986], [101, 669],
              [918, 599], [470, 78], [860, 965], [870, 845], [810, 888],
              [446, 122], [645, 880], [599, 92], [181, 487], [688, 610],
              [916, 249], [185, 747], [492, 681], [3, 352], [667, 456],
              [21, 937], [55, 491], [15, 915], [457, 238], [761, 267],
              [478, 559], [741, 123], [439, 692], [568, 972], [180, 256],
              [935, 96], [858, 120], [195, 702], [801, 198], [54, 820],
              [654, 76], [757, 62], [567, 772], [977, 376], [362, 90],
              [995, 840], [1, 88], [316, 793], [781, 884], [765, 961],
              [492, 700], [57, 702], [172, 604], [404, 325], [803, 459],
              [145, 809], [887, 902], [871, 454], [27, 201], [183, 741],
              [643, 178], [582, 645], [267, 250], [438, 48], [134, 555],
              [361, 978], [608, 770], [681, 780], [374, 437], [106, 529],
              [896, 603], [339, 135], [858, 562], [590, 885], [115, 125],
              [626, 759], [303, 560], [404, 922], [810, 842], [970, 296],
              [397, 683], [627, 5], [453, 308], [138, 828], [745, 596],
              [709, 994], [199, 48], [129, 57], [963, 71], [294,
                                                            78], [196, 273],
              [189, 852], [833, 593], [774, 996], [787, 97], [644, 537],
              [780, 271], [894, 234], [579, 32], [414, 677], [628, 123],
              [23, 180], [524, 504], [589, 487], [576, 884], [917, 124],
              [157, 107], [976, 342], [52, 103], [690, 840], [200, 335],
              [377, 980], [606, 271], [566, 538], [656, 980], [567, 636],
              [456, 590], [168, 980], [94, 758], [819, 22], [994, 88],
              [147, 503], [195, 475], [197, 600], [578, 888], [792, 130],
              [223, 169], [463, 181], [792, 29], [719, 800], [10, 286],
              [789, 466], [228, 957], [798, 323], [715, 617], [697, 61],
              [705, 196], [564, 253], [672, 762], [205, 602], [650, 997],
              [85, 225], [518, 548], [406, 662], [577, 478], [463, 939],
              [116, 252], [757, 345], [561, 555], [20, 277], [524, 717],
              [690, 582], [914, 255], [187, 938], [17, 392], [892, 19],
              [741, 977], [596, 259], [525, 2], [273, 455], [832, 736],
              [394, 949], [340, 504], [294, 902], [59, 314], [531, 936],
              [383, 221], [870, 297], [828, 57], [587, 197], [801, 480],
              [568, 894], [457, 164], [153, 335], [519, 426], [790, 351],
              [515, 536], [652, 207], [40, 946], [461, 452], [612, 344],
              [388, 996], [918, 610], [645, 746], [19, 233], [296, 820],
              [65, 864], [66, 522], [29, 219], [209, 548], [997, 351],
              [251, 864], [888, 904], [72, 928], [202, 885], [732, 815],
              [230, 472], [163, 148], [82, 160], [246, 101], [745, 542],
              [273, 810], [407, 339]]

    profile = Profile()
    profile.runcall(s.numberOfBoomerangs, points=points)
    profile.print_stats()

    print("-" * 32)

    profile = Profile()
    profile.runcall(s.numberOfBoomerangs2, points=points)
    profile.print_stats()
コード例 #33
0
from tic_tac_toe import TicTacToe
from random_ai import RandomAI
from minimax_ai import MinimaxAI

counters = {-1: 0, 0: 0, 1: 0}
n_games = int(1e2)


def run_trials():
    for i in range(n_games):
        ttt = TicTacToe()
        x_ai = MinimaxAI(ttt)
        o_ai = RandomAI(ttt)
        ttt.o_ai = o_ai
        ttt.x_ai = x_ai

        result = ttt.loop()
        counters[result] += 1


from cProfile import Profile

profiler = Profile()
profiler.runcall(run_trials)

profiler.print_stats('cumulative')

print(
    f"stats: out of {n_games} games, x has won {counters[1]} times, o - {counters[-1]} times, and there were "
    f"{counters[0]} draws.")
コード例 #34
0
        float(len(profiling_get_actions_each_number_returned))
    total_planning_phases = len(profiling_get_actions_each_call)
    most_frequent_chain = []
    root_node = policy
    while (not root_node is None):
        children = root_node.get_frequently_accessed_children()
        if (len(children) > 0):
            most_frequent_chain.append(children[0])
            root_node = children[0][0]
        else:
            root_node = None

    stdout.write("\n---------------Profiling----------------\n")
    stdout.write("Profiler information:\n")
    stdout.write("State building profiler:\n")
    build_state_profiler.print_stats()
    stdout.write("Get actions profiler:\n")
    get_actions_profiler.print_stats()
    stdout.write("Action selection profiler:\n")
    action_select_profiler.print_stats()
    stdout.write("Average number of calls to get_action "
                 "per planning step: %.2f\n" % (average_calls))
    stdout.write("Average number of regressions returned "
                 "per planning step: %.2f\n" % (average_len_reg))
    stdout.write("Total number of planning phases: %d\n" %
                 (total_planning_phases))
    stdout.write("Trace of most frequently traversed path:\n")
    root_node = policy
    for node_tuple in most_frequent_chain:
        var_index = root_node.var_index
        var_value = node_tuple[1]
コード例 #35
0
ファイル: test_everything.py プロジェクト: egon1024/scheme
def profile_while_timing(statement, setup=Environment, number=5000):
    profile = Profile()
    profile.enable()
    timeit.timeit(statement, setup, number=number)
    profile.disable()
    profile.print_stats('cumtime')
コード例 #36
0
                    '''
    graph2 = [list(row) for row in nodes_map_raw.split()]
    nr = len(graph2)
    nc = len(graph2[0])
    bdbfs = BiDirBFS(nodes_map_raw)
    for i in bdbfs.step():
        pass
    if bdbfs.path:
        for y in xrange(nr):
            for x in xrange(nc):
                if (x, y) == bdbfs.source:
                    print 'S',
                elif (x, y) == bdbfs.target:
                    print 'T',
                elif (x, y) in bdbfs.path:
                    print '.',
                elif graph2[y][x] == BLOCKED:
                    print 'X',
                else:
                    print ' ',
            print 
        print 'Route length:', len(bdbfs.path)
    else:
        print 'Failed to find the path'

if __name__ == '__main__':
    from cProfile import Profile
    p = Profile()
    p.runcall(_test)
    p.print_stats(sort = 1)
コード例 #37
0
def profile(call, *args, **kwargs):
    profiler = Profile()
    profiler.runcall(call, *args, **kwargs)
    profiler.print_stats()
コード例 #38
0
ファイル: python_profiler.py プロジェクト: daluzi/Tools
        ret += i * i + math.sqrt(i)
    return ret


def main():
    for i in range(100000):
        if i % 10000 == 0:
            bar()
        else:
            foo()


if __name__ == '__main__':
    prof = Profile()
    prof.runcall(main)
    prof.print_stats()
    #prof.dump_stats('test.prof') # dump profile result to test.prof
    '''
       Ordered by: standard name
    
    ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    99990    0.015    0.000    0.062    0.000 python_profiler.py:11(foo)
    99990    0.014    0.000    0.048    0.000 python_profiler.py:14(foo1)
    99990    0.014    0.000    0.034    0.000 python_profiler.py:17(foo2)
    99990    0.014    0.000    0.020    0.000 python_profiler.py:20(foo3)
    99990    0.006    0.000    0.006    0.000 python_profiler.py:23(foo4)
       10    0.019    0.002    0.027    0.003 python_profiler.py:26(bar)
        1    0.017    0.017    0.107    0.107 python_profiler.py:32(main)
    100000    0.009    0.000    0.009    0.000 {built-in method math.sqrt}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
        
コード例 #39
0
ファイル: astar.py プロジェクト: peakcyber/OpenAnt
    a = AStar(nodes_map_raw)
    for i in a.step():
        pass
    path = a.path
    start = a.source
    end = a.target
    if path:
        for y in xrange(nr):
            for x in xrange(nc):
                if (x, y) == start:
                    print 'S',
                elif (x, y) == end:
                    print 'T',
                elif (x, y) in path:
                    print '.',
                elif graph2[y][x] == BLOCKED:
                    print 'X',
                else:
                    print ' ',
            print
        print 'Route length:', len(path)
    else:
        print 'Failed to find the path'


if __name__ == '__main__':
    from cProfile import Profile
    p = Profile()
    p.runcall(_test)
    p.print_stats(sort=1)
コード例 #40
0
def main():
    with open("CTRL", mode="r") as fp:
        site_t = None
        class_t = None
        plat_n = 0
        for line in fp:
            word = line.split()
            if word[0] == "STRUC":
                for w in word:
                    worde = w.split("=")
                    if worde[0] == "ALAT":
                        alat = float(worde[1])
                plat_n = 4
            if word[0] == "DIM":
                for w in word:
                    worde = w.split("=")
                    if worde[0] == "NBAS":
                        nbas = int(worde[1])
                    if worde[0] == "NCLASS":
                        nclass = int(worde[1])
#  print(alat,nbas)
            if plat_n == 3:
                Plat = np.zeros((3, 3))
                if len(word) == 3:
                    worde = word[0].split("=")
                    Plat[0][0] = float(worde[1])
                    Plat[0][1] = float(word[1])
                    Plat[0][2] = float(word[2])
                else:
                    Plat[0][0] = float(word[1])
                    Plat[0][1] = float(word[2])
                    Plat[0][2] = float(word[3])
            elif plat_n == 2:
                Plat[1][0] = float(word[0])
                Plat[1][1] = float(word[1])
                Plat[1][2] = float(word[2])
            elif plat_n == 1:
                Plat[2][0] = float(word[0])
                Plat[2][1] = float(word[1])
                Plat[2][2] = float(word[2])
            plat_n -= 1
            if word[0] == "CLASS":
                class_t = True
                class_n = nclass
                allclass_ctrl = []
            if class_t:
                if len(word) < 5:
                    continue
                if class_n == nclass:
                    if word[2] == "Z=":
                        class_ctrl = Class_ctrl(word[1].split("=")[1], word[3],
                                                word[4].split("=")[1])
                    else:
                        class_ctrl = Class_ctrl(word[1].split("=")[1],
                                                word[2].split("=")[1],
                                                word[3].split("=")[1])
                    allclass_ctrl.append(class_ctrl)
                else:
                    if word[1] == "Z=":
                        class_ctrl = Class_ctrl(word[0].split("=")[1], word[2],
                                                word[3].split("=")[1])
                    else:
                        class_ctrl = Class_ctrl(word[0].split("=")[1],
                                                word[1].split("=")[1],
                                                word[2].split("=")[1])
                    allclass_ctrl.append(class_ctrl)
                class_n -= 1
                if class_n == 0:
                    class_t = False
            if word[0] == "SITE":
                site_t = True
                site_n = nbas
                allatom = []
            if site_t:
                if site_n == nbas:
                    atom = Atom()
                    for w in word:
                        worde = w.split("=")
                        if worde[0] == "ATOM":
                            atom.name = worde[1]
                    if len(word) == 5:
                        worde = word[2].split("=")
                        atom.pos = np.array(
                            [float(worde[1]),
                             float(word[3]),
                             float(word[4])])
                    elif len(word) == 6:
                        atom.pos = np.array(
                            [float(word[3]),
                             float(word[4]),
                             float(word[5])])
                    else:
                        print("error")
                        sys.exit()
                    allatom.append(atom)
                else:
                    atom = Atom()
                    atom.name = (word[0].split("=")[1])
                    if len(word) == 4:
                        worde = word[1].split("=")
                        atom.pos = np.array(
                            [float(worde[1]),
                             float(word[2]),
                             float(word[3])])
                    elif len(word) == 5:
                        atom.pos = np.array(
                            [float(word[2]),
                             float(word[3]),
                             float(word[4])])
                    else:
                        print("error")
                        sys.exit()
                    allatom.append(atom)
                site_n -= 1
                if site_n == 0:
                    site_t = False
            if site_t == False:
                break

    for i in allatom:
        i.ctrltuika(allclass_ctrl)
    for i in range(len(allatom)):
        print(allatom[i].name, allatom[i].ze, allatom[i].rad, allatom[i].pos)


#  print(Plat)
#  sys.exit()
#  Pos_np=np.array(Pos)
#  print(Atom)
#  print(Pos_np)
#  Plat=Plat*alat*BOHR
#  Pos_np=Pos_np*alat*BOHR
#  print(Pos_np)

    print("which is center ?(Atomname or Coordinate)")
    centeratom = input().split()
    c = 0
    origincart = np.array([0., 0., 0.])
    if len(centeratom) == 1:
        for i in range(nbas):
            if centeratom == allatom[i].name:
                c = i
                break
        origincart = allatom[c].pos
    elif len(centeratom) == 3:
        for i in range(3):
            origincart[i] = float(centeratom[i])
    else:
        print("error")
        sys.exit()

    print("How is clustersize ? (please input cluster radius)")
    clradius = float(input())

    with open("cluster.in", mode="w") as clin:
        for i in range(3):
            clin.write(str("{:>11}".format("{:.8f}".format(Plat[i][0]))))
            clin.write(str("{:>11}".format("{:.8f}".format(Plat[i][1]))))
            clin.write(str("{:>11}".format("{:.8f}".format(Plat[i][2]))))
            clin.write("\n")

        clin.write(" 0 0 0\n")
        clin.write(str("{:>12}".format("{:.8f}".format(allatom[c].pos[0]))))
        clin.write(str("{:>12}".format("{:.8f}".format(allatom[c].pos[1]))))
        clin.write(str("{:>12}".format("{:.8f}".format(allatom[c].pos[2]))))
        clin.write("\n")
        clin.write(" " + str(nbas) + "\n")
        for i in range(nbas):
            clin.write(str("{:>3}".format(allatom[i].name)))
            clin.write(str("{:>12}".format("{:.8f}".format(
                allatom[i].pos[0]))))
            clin.write(str("{:>12}".format("{:.8f}".format(
                allatom[i].pos[1]))))
            clin.write(str("{:>12}".format("{:.8f}".format(
                allatom[i].pos[2]))))
            clin.write("\n")
        clin.write(str("{:.4f}".format(alat * BOHR)) + "\n")
        for i in range(3):
            clin.write(str(clradius) + "\n")

    sys.exit()

    cutoff = clradius
    i0max = int(cutoff * FACTOR / np.sqrt(np.sum(Plat[0]**2)))
    i1max = int(cutoff * FACTOR / np.sqrt(np.sum(Plat[1]**2)))
    i2max = int(cutoff * FACTOR / np.sqrt(np.sum(Plat[2]**2)))

    clusteratom = []
    y = np.array([0., 0., 0.])
    n = 0
    pr = Profile()
    pr.enable()
    t1 = time.time()
    for i0 in range(-i0max, i0max + 1):
        for i1 in range(-i1max, i1max + 1):
            for i2 in range(-i2max, i2max + 1):
                for k in range(nbas):
                    y = i0 * Plat[0] + i1 * Plat[1] + i2 * Plat[2] + allatom[
                        k].pos - origincart
                    y *= alat * BOHR
                    if np.sqrt(sum(y**2)) < clradius:
                        atom = Atom()
                        atom.name = allatom[k].name
                        atom.ze = allatom[k].ze
                        atom.pos = copy.deepcopy(y)
                        clusteratom.append(atom)
                        n += 1
    print(n)
    t2 = time.time()
    print(t2 - t1)
    sys.exit()
    pr.disable()
    pr.print_stats()
    sys.exit()
    for i in range(len(clusteratom)):
        print(clusteratom[i].name, clusteratom[i].ze, clusteratom[i].pos)