-
Notifications
You must be signed in to change notification settings - Fork 259
/
threaded_read.py
62 lines (56 loc) · 1.65 KB
/
threaded_read.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
from netCDF4 import Dataset
from numpy.testing import assert_array_equal, assert_array_almost_equal
import numpy as np
import threading
import queue
import time
# demonstrate reading of different files from different threads.
# Releasing the Global Interpreter Lock (GIL) when calling the
# netcdf C library for read operations speeds up the reads
# when threads are used (issue 369).
# Test script contributed by Ryan May of Unidata.
# Make some files
nfiles = 4
fnames = []; datal = []
for i in range(nfiles):
fname = 'test%d.nc' % i
fnames.append(fname)
nc = Dataset(fname, 'w')
data = np.random.randn(500, 500, 500)
datal.append(data)
nc.createDimension('x', 500)
nc.createDimension('y', 500)
nc.createDimension('z', 500)
var = nc.createVariable('grid', 'f', ('x', 'y', 'z'))
var[:] = data
nc.close()
# Queue them up
items = queue.Queue()
for data,fname in zip(datal,fnames):
items.put(fname)
# Function for threads to use
def get_data(serial=None):
if serial is None: # if not called from a thread
fname = items.get()
else:
fname = fnames[serial]
nc = Dataset(fname, 'r')
data2 = nc.variables['grid'][:]
# make sure the data is correct
#assert_array_almost_equal(data2,datal[int(fname[4])])
nc.close()
if serial is None:
items.task_done()
# Time it (no threading).
start = time.time()
for i in range(nfiles):
get_data(serial=i)
end = time.time()
print('no threads, time = ',end - start)
# with threading.
start = time.time()
for i in range(nfiles):
threading.Thread(target=get_data).start()
items.join()
end = time.time()
print('with threading, time = ',end - start)