matlab_conversion.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. __author__ = "Christian Heider Nielsen"
  4. __doc__ = r"""
  5. Created on 14-02-2021
  6. """
  7. __all__ = []
  8. import timeit
  9. def conversion_benchmark() -> None:
  10. """
  11. :rtype: None
  12. """
  13. # Numpy to matlab
  14. print(
  15. "\nCompare Numpy to matlab conversion strategy : (a bit long with several matlab.engine opening)"
  16. )
  17. setup_np2mat = (
  18. "import numpy\n"
  19. "import matlab\n"
  20. "from draugr.matlab_utilities import matlab_to_ndarray, ndarray_to_matlab\n"
  21. "import array\n"
  22. "np_a=numpy.random.uniform(size=(10000))*(.5+0.1236*1j) \n"
  23. )
  24. print(
  25. " > From matlab.double(np_a.tolist()) : "
  26. + str(
  27. timeit.timeit(
  28. "mat_a = matlab.double(np_a.real.tolist())",
  29. setup=setup_np2mat,
  30. number=100,
  31. )
  32. )
  33. + " s"
  34. )
  35. print(
  36. " > From ndarray_to_matlab [use pre alloc] : "
  37. + str(
  38. timeit.timeit(
  39. "mat_a = ndarray_to_matlab(np_a)", setup=setup_np2mat, number=100
  40. )
  41. )
  42. + " s"
  43. )
  44. # Matlab to numpy
  45. print("\nCompare matlab to numpy conversition strategy :")
  46. setup_tolist = (
  47. "import numpy\n"
  48. "import matlab\n"
  49. "from draugr.matlab_utilities import matlab_to_ndarray, ndarray_to_matlab\n"
  50. "eng = matlab.engine.start_matlab()\n"
  51. "mrd = eng.rand(matlab.int64([1,10000]),nargout=1)\n"
  52. )
  53. print(
  54. " > From numpy.array : "
  55. + str(
  56. timeit.timeit(
  57. "nprd = numpy.array(mrd,dtype = float) ", setup=setup_tolist, number=100
  58. )
  59. )
  60. + " s"
  61. )
  62. print(
  63. " > From numpy.asarray [use _data] : "
  64. + str(
  65. timeit.timeit(
  66. "nprd = numpy.asarray(mrd._data,dtype = float) ",
  67. setup=setup_tolist,
  68. number=100,
  69. )
  70. )
  71. + " s"
  72. )
  73. print(
  74. " > From matlab_to_ndarray [use _data buffer] : "
  75. + str(
  76. timeit.timeit(
  77. "nprd = matlab_to_ndarray(mrd) ", setup=setup_tolist, number=100
  78. )
  79. )
  80. + " s"
  81. )
  82. setup_tolist_cpx = (
  83. "import numpy\n"
  84. "import matlab\n"
  85. "from draugr.matlab_utilities import matlab_to_ndarray, ndarray_to_matlab\n"
  86. "eng = matlab.engine.start_matlab()\n"
  87. "mrd = eng.log(eng.linspace(-1.,1.,10000.))\n"
  88. )
  89. print(
  90. " > From matlab_to_ndarray [use _real _imag buffer complex] : "
  91. + str(
  92. timeit.timeit(
  93. "nprd = matlab_to_ndarray(mrd) ", setup=setup_tolist_cpx, number=100
  94. )
  95. )
  96. + " s"
  97. )
  98. if __name__ == "__main__":
  99. conversion_benchmark()