|
1 | 1 | # [Performance tips](@id performance_tips)
|
2 | 2 |
|
3 |
| -* Reading data from a file is not type-stable, because the type of the output of the read operation is dependent on the type defined in the NetCDF files and the value of various attribute (like `scale_factor`, `add_offset` and `units` for time conversion). All this information cannot be inferred from a static analysis of the source code. It is therefore recommended to use [type annotation](https://docs.julialang.org/en/v1/manual/types/index.html#Type-Declarations-1) if resulting type of a read operation in known: |
| 3 | +* Reading data from a file is not type-stable, because the type of the output of the read operation is dependent on the type defined in the NetCDF files and the value of various attribute (like `scale_factor`, `add_offset` and `units` for time conversion). All this information cannot be inferred from a static analysis of the source code. It is therefore recommended to use [type annotation](https://docs.julialang.org/en/v1/manual/types/index.html#Type-Declarations-1) if the resulting type of a read operation in known: |
4 | 4 |
|
5 | 5 | ```julia
|
6 | 6 | ds = NCDataset("file.nc")
|
7 | 7 | nctemp = ds["temp"]
|
8 |
| -temp = nctemp[:,:] :: Array{Float64,2} |
9 |
| -# or |
10 |
| -# call_barrier_function(nctemp) |
| 8 | +temp = nctemp[:,:] :: Array{Float32,2} |
11 | 9 |
|
12 |
| -Alternatively, one can also use so called "[function barriers](https://docs.julialang.org/en/v1/manual |
13 |
| -# call_barrier_function(temp) |
14 |
| -close(ds) |
15 |
| -```/performance-tips/index.html#kernel-functions-1)" or the in-place `NCDatasets.load!` function (which is unexported, so it has to be prefixed with the module name): |
| 10 | +# heavy computation using temp |
| 11 | +# ... |
| 12 | +``` |
| 13 | + |
| 14 | +Alternatively, one can also use so-called [function barriers](https://docs.julialang.org/en/v1/manual/performance-tips/index.html#kernel-functions-1) |
| 15 | +since the function `heavy_computation` will be specialized based on the type its input parameters. |
| 16 | + |
| 17 | + |
| 18 | +```julia |
| 19 | +function heavy_computation(temp) |
| 20 | +# heavy computation using temp |
| 21 | +# ... |
| 22 | +end |
| 23 | + |
| 24 | +ds = NCDataset("file.nc") |
| 25 | +nctemp = ds["temp"] |
| 26 | +temp = nctemp[:,:] |
| 27 | +output = heavy_computation(temp) |
| 28 | +``` |
| 29 | + |
| 30 | +Calling the barrier function with `nctemp` would also be type-stable. |
| 31 | +Using the in-place `NCDatasets.load!` function (which is unexported, so it has to be prefixed with the module name) does also lead to type-stable code and allows to reuse a memory buffer: |
16 | 32 |
|
17 | 33 | ```julia
|
18 | 34 | ds = NCDataset("file.nc")
|
19 | 35 |
|
20 |
| -temp = zeros(10,20) |
| 36 | +temp = zeros(Float32,10,20) |
21 | 37 | NCDatasets.load!(variable(ds,"temp"),temp,:,:)
|
22 | 38 | ```
|
23 | 39 |
|
|
0 commit comments