本文整理汇总了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
示例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()
示例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
示例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()
示例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()
示例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
示例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
示例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
示例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
示例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
示例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 ---------------------------
示例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
示例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
示例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)
示例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), [])