當前位置: 首頁>>代碼示例>>Python>>正文


Python gc.collect方法代碼示例

本文整理匯總了Python中gc.collect方法的典型用法代碼示例。如果您正苦於以下問題:Python gc.collect方法的具體用法?Python gc.collect怎麽用?Python gc.collect使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在gc的用法示例。


在下文中一共展示了gc.collect方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _place_electrodes

# 需要導入模塊: import gc [as 別名]
# 或者: from gc import collect [as 別名]
def _place_electrodes(self, fix_th=True):
        """ Add the defined electrodes to a mesh

        Parameters:
        ------------
        fn_out: str
            name of output file
        """
        w_elec = copy.deepcopy(self.mesh)
        w_elec.fix_tr_node_ordering()
        electrode_surfaces = [None for i in range(len(self.electrode))]
        for i, el in enumerate(self.electrode):
            logger.info('Placing Electrode:\n{0}'.format(str(el)))
            w_elec, n = el.add_electrode_to_mesh(w_elec)
            electrode_surfaces[i] = n

        w_elec.fix_th_node_ordering()
        w_elec.fix_tr_node_ordering()
        if fix_th:
            logger.info('Improving mesh quality')
            w_elec.fix_thin_tetrahedra()

        gc.collect()
        return w_elec, electrode_surfaces 
開發者ID:simnibs,項目名稱:simnibs,代碼行數:26,代碼來源:sim_struct.py

示例2: loadW2V

# 需要導入模塊: import gc [as 別名]
# 或者: from gc import collect [as 別名]
def loadW2V(self,emb_path, type="bin"):
        print("Loading W2V data...")
        num_keys = 0
        if type=="textgz":
            # this seems faster than gensim non-binary load
            for line in gzip.open(emb_path):
                l = line.strip().split()
                st=l[0].lower()
                self.pre_emb[st]=np.asarray(l[1:])
            num_keys=len(self.pre_emb)
        if type=="text":
            # this seems faster than gensim non-binary load
            for line in open(emb_path):
                l = line.strip().split()
                st=l[0].lower()
                self.pre_emb[st]=np.asarray(l[1:])
            num_keys=len(self.pre_emb)
        else:
            self.pre_emb = Word2Vec.load_word2vec_format(emb_path,binary=True)
            self.pre_emb.init_sims(replace=True)
            num_keys=len(self.pre_emb.vocab)
        print("loaded word2vec len ", num_keys)
        gc.collect() 
開發者ID:dhwajraj,項目名稱:deep-siamese-text-similarity,代碼行數:25,代碼來源:input_helpers.py

示例3: test_close_auto_generated_session

# 需要導入模塊: import gc [as 別名]
# 或者: from gc import collect [as 別名]
def test_close_auto_generated_session(self, mocker):
        # Setup
        import requests
        import gc

        session_mock = mocker.Mock(spec=requests.Session)
        session_mock.request.return_value = "response"
        session_cls_mock = mocker.patch("requests.Session")
        session_cls_mock.return_value = session_mock

        # Run
        client = requests_.RequestsClient()
        client.send(("method", "url", {}))
        del client
        gc.collect()

        assert session_mock.close.call_count == 1 
開發者ID:prkumar,項目名稱:uplink,代碼行數:19,代碼來源:test_clients.py

示例4: test_close_auto_created_session

# 需要導入模塊: import gc [as 別名]
# 或者: from gc import collect [as 別名]
def test_close_auto_created_session(self, mocker):
        # Setup
        import asyncio
        import gc
        import aiohttp

        mock_session = mocker.Mock(spec=aiohttp.ClientSession)
        session_cls_mock = mocker.patch("aiohttp.ClientSession")
        session_cls_mock.return_value = mock_session

        positionals = [1]
        keywords = {"keyword": 2}

        # Run: Create client
        client = aiohttp_.AiohttpClient.create(*positionals, **keywords)

        # Run: Get session
        loop = asyncio.get_event_loop()
        loop.run_until_complete(asyncio.ensure_future(client.session()))

        # Verify: session created with args
        session_cls_mock.assert_called_with(*positionals, **keywords)
        del client
        gc.collect()
        session_cls_mock.return_value.close.assert_called_with() 
開發者ID:prkumar,項目名稱:uplink,代碼行數:27,代碼來源:test_clients.py

示例5: fix_tr_node_ordering

# 需要導入模塊: import gc [as 別名]
# 或者: from gc import collect [as 別名]
def fix_tr_node_ordering(self):
        ''' Fixes the node ordering of the triangles in-place '''
        corresponding = self.find_corresponding_tetrahedra()
        triangles = np.where(self.elm.elm_type == 2)[0]

        triangles = triangles[corresponding != -1]
        corresponding = corresponding[corresponding != -1]

        normals = self.triangle_normals().value[triangles]
        baricenters = self.elements_baricenters().value
        pos_bar = baricenters[corresponding - 1] - baricenters[triangles]

        dotp = np.einsum('ij, ij -> i', normals, pos_bar)
        switch = triangles[dotp > 0]

        tmp = np.copy(self.elm.node_number_list[switch, 1])
        self.elm.node_number_list[switch, 1] = self.elm.node_number_list[switch, 0]
        self.elm.node_number_list[switch, 0] = tmp
        del tmp
        gc.collect() 
開發者ID:simnibs,項目名稱:simnibs,代碼行數:22,代碼來源:mesh_io.py

示例6: unload_group

# 需要導入模塊: import gc [as 別名]
# 或者: from gc import collect [as 別名]
def unload_group(chat_id):
    global gcache, gc_counter
    try:
        with open("markov/chat_" + str(chat_id) + ".dat", "wb") as f:
            pickle.dump(groups[chat_id], f)
            groups[chat_id] = None
            del groups[chat_id]
        gcache.remove(chat_id)
        gc_counter -= 1
        if gc_counter < 1:
            gc_counter = gc_every_unload
            gc.collect()
    except KeyboardInterrupt as e:
        raise e
    except:
        pass 
開發者ID:39bit,項目名稱:Markov_Bot,代碼行數:18,代碼來源:markov_bot.py

示例7: _wrapper

# 需要導入模塊: import gc [as 別名]
# 或者: from gc import collect [as 別名]
def _wrapper(method, check_steps_end):
        if hasattr(method, '_already_decorated') and method._already_decorated:
            return method

        @wraps(method)
        def wrapped(*args, **kwargs):
            MolerTest._steps_start()
            caught_exception = None
            try:
                result = method(*args, **kwargs)
            except Exception as exc:
                caught_exception = exc
            finally:
                MolerTest._check_exceptions_occured(caught_exception)
                if check_steps_end:
                    MolerTest._check_steps_end()
            gc.collect()
            return result

        wrapped._already_decorated = True
        return wrapped 
開發者ID:nokia,項目名稱:moler,代碼行數:23,代碼來源:moler_test.py

示例8: test_subscription_doesnt_block_subscriber_to_be_garbage_collected

# 需要導入模塊: import gc [as 別名]
# 或者: from gc import collect [as 別名]
def test_subscription_doesnt_block_subscriber_to_be_garbage_collected():
    from moler.publisher import Publisher

    notifier = Publisher()
    garbage_collected_subscribers = []

    class GcSubscriber(object):
        def __del__(self):
            garbage_collected_subscribers.append('Subscriber')

    subscr = GcSubscriber()
    notifier.subscribe(subscr)

    del subscr
    gc.collect()

    assert 'Subscriber' in garbage_collected_subscribers 
開發者ID:nokia,項目名稱:moler,代碼行數:19,代碼來源:test_publisher.py

示例9: test_garbage_collected_subscriber_is_not_notified

# 需要導入模塊: import gc [as 別名]
# 或者: from gc import collect [as 別名]
def test_garbage_collected_subscriber_is_not_notified():
    from moler.publisher import Publisher

    notifier = Publisher()
    received_data = []

    class GcSubscriber(object):
        def __call__(self, data):
            received_data.append(data)

    subscr1 = GcSubscriber()
    subscr2 = GcSubscriber()
    notifier.subscribe(subscriber=subscr1)
    notifier.subscribe(subscriber=subscr2)

    del subscr1
    gc.collect()

    notifier.notify_subscribers("data")
    assert len(received_data) == 1 
開發者ID:nokia,項目名稱:moler,代碼行數:22,代碼來源:test_publisher.py

示例10: test_subscription_doesnt_block_subscriber_to_be_garbage_collected

# 需要導入模塊: import gc [as 別名]
# 或者: from gc import collect [as 別名]
def test_subscription_doesnt_block_subscriber_to_be_garbage_collected():
    from moler.threaded_moler_connection import ThreadedMolerConnection

    moler_conn = ThreadedMolerConnection()
    garbage_collected_subscribers = []

    class Subscriber(object):
        def __del__(self):
            garbage_collected_subscribers.append('Subscriber')

    class CloseSubscriber(object):
        pass

    subscr = Subscriber()
    close_subscr = CloseSubscriber()
    moler_conn.subscribe(subscr, close_subscr)

    del subscr
    gc.collect()

    assert 'Subscriber' in garbage_collected_subscribers 
開發者ID:nokia,項目名稱:moler,代碼行數:23,代碼來源:test_connection.py

示例11: test_garbage_collected_subscriber_is_not_notified

# 需要導入模塊: import gc [as 別名]
# 或者: from gc import collect [as 別名]
def test_garbage_collected_subscriber_is_not_notified():
    from moler.threaded_moler_connection import ThreadedMolerConnection

    moler_conn = ThreadedMolerConnection()
    received_data = []

    class Subscriber(object):
        def __call__(self, data, time_recv):
            received_data.append(data)

    subscr1 = Subscriber()
    subscr2 = Subscriber()
    moler_conn.subscribe(observer=subscr1, connection_closed_handler=do_nothing_func)
    moler_conn.subscribe(observer=subscr2, connection_closed_handler=do_nothing_func)

    del subscr1
    gc.collect()

    moler_conn.data_received("data", datetime.datetime.now())
    MolerTest.sleep(1, True)  # Processing in separate thread so have to wait.
    assert len(received_data) == 1

# --------------------------- resources --------------------------- 
開發者ID:nokia,項目名稱:moler,代碼行數:25,代碼來源:test_connection.py

示例12: test_structured_object_indexing

# 需要導入模塊: import gc [as 別名]
# 或者: from gc import collect [as 別名]
def test_structured_object_indexing(self, shape, index, items_changed,
                                        dt, pat, count, singleton):
        """Structured object reference counting for advanced indexing."""
        zero = 0
        one = 1

        arr = np.zeros(shape, dt)

        gc.collect()
        before_zero = sys.getrefcount(zero)
        before_one = sys.getrefcount(one)
        # Test item getting:
        part = arr[index]
        after_zero = sys.getrefcount(zero)
        assert after_zero - before_zero == count * items_changed
        del part
        # Test item setting:
        arr[index] = one
        gc.collect()
        after_zero = sys.getrefcount(zero)
        after_one = sys.getrefcount(one)
        assert before_zero - after_zero == count * items_changed
        assert after_one - before_one == count * items_changed 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:25,代碼來源:test_dtype.py

示例13: test_structured_object_take_and_repeat

# 需要導入模塊: import gc [as 別名]
# 或者: from gc import collect [as 別名]
def test_structured_object_take_and_repeat(self, dt, pat, count, singleton):
        """Structured object reference counting for specialized functions.
        The older functions such as take and repeat use different code paths
        then item setting (when writing this).
        """
        indices = [0, 1]

        arr = np.array([pat] * 3, dt)
        gc.collect()
        before = sys.getrefcount(singleton)
        res = arr.take(indices)
        after = sys.getrefcount(singleton)
        assert after - before == count * 2
        new = res.repeat(10)
        gc.collect()
        after_repeat = sys.getrefcount(singleton)
        assert after_repeat - after == count * 2 * 10 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:19,代碼來源:test_dtype.py

示例14: test_leak_in_structured_dtype_comparison

# 需要導入模塊: import gc [as 別名]
# 或者: from gc import collect [as 別名]
def test_leak_in_structured_dtype_comparison(self):
        # gh-6250
        recordtype = np.dtype([('a', np.float64),
                               ('b', np.int32),
                               ('d', (str, 5))])

        # Simple case
        a = np.zeros(2, dtype=recordtype)
        for i in range(100):
            a == a
        assert_(sys.getrefcount(a) < 10)

        # The case in the bug report.
        before = sys.getrefcount(a)
        u, v = a[0], a[1]
        u == v
        del u, v
        gc.collect()
        after = sys.getrefcount(a)
        assert_equal(before, after) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:22,代碼來源:test_regression.py

示例15: test_env_dirty

# 需要導入模塊: import gc [as 別名]
# 或者: from gc import collect [as 別名]
def test_env_dirty(self):
        self.odoo.config['auto_commit'] = False

        def test_record_garbarge_collected():
            user_ids = self.odoo.env['res.users'].search([('id', '!=', 1)])
            user = self.user_obj.browse(user_ids[0])
            self.assertNotIn(user, self.odoo.env.dirty)
            self.assertNotIn(user, user.env.dirty)
            user.name = "Joe"
            self.assertIn(user, self.odoo.env.dirty)
            self.assertIn(user, user.env.dirty)

        test_record_garbarge_collected()
        # Ensure the record has been garbage collected for the next test
        import gc

        gc.collect()
        self.assertEqual(list(self.odoo.env.dirty), []) 
開發者ID:OCA,項目名稱:odoorpc,代碼行數:20,代碼來源:test_env.py


注:本文中的gc.collect方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。