You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

MemoryMonitor.cs 2.9 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using System;
  2. using System.Diagnostics;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using Tensorflow.NumPy;
  6. using static Tensorflow.Binding;
  7. using static Tensorflow.KerasApi;
  8. namespace Tensorflow
  9. {
  10. public class MemoryMonitor
  11. {
  12. public void WarmUp()
  13. {
  14. var x1 = tf.Variable(10, name: "x");
  15. tf.compat.v1.disable_eager_execution();
  16. var input = np.array(4);
  17. var nd = tf.reshape(input, new int[] { 1, 1});
  18. var z = nd[0, 0];
  19. while (true)
  20. {
  21. var x = tf.placeholder(tf.float64, shape: (1024, 1024));
  22. var log = tf.log(x);
  23. var sess = tf.Session();
  24. var ones = np.ones((1024, 1024), dtype: np.float64);
  25. var o = sess.run(log, new FeedItem(x, ones));
  26. // Thread.Sleep(1);
  27. }
  28. Shape shape = (1, 32, 32, 3);
  29. np.arange(shape.size).astype(np.float32).reshape(shape.dims);
  30. print($"tensorflow native version: v{tf.VERSION}");
  31. tf.Context.ensure_initialized();
  32. var a = tf.constant(np.ones((10, 10)));
  33. var b = tf.Variable(a);
  34. var c = tf.Variable(b);
  35. var d = b * c;
  36. print(d.numpy());
  37. GC.Collect();
  38. GC.WaitForPendingFinalizers();
  39. }
  40. public void Execute(int epoch, int iterate, Action<int, int> process)
  41. {
  42. GC.Collect();
  43. GC.WaitForPendingFinalizers();
  44. var initialTotalMemory = Process.GetCurrentProcess().PrivateMemorySize64;
  45. print($"{process.Method.Name} started...");
  46. for (int i = 0; i < epoch; i++)
  47. {
  48. var initialMemory = Process.GetCurrentProcess().PrivateMemorySize64;
  49. for (int j = 0; j < iterate; j++)
  50. process(i, j);
  51. keras.backend.clear_session();
  52. GC.Collect();
  53. GC.WaitForPendingFinalizers();
  54. var finalMemory = Process.GetCurrentProcess().PrivateMemorySize64;
  55. print($"Epoch {i}: {Format(finalMemory - initialMemory)}.");
  56. }
  57. var finalTotalMemory = Process.GetCurrentProcess().PrivateMemorySize64;
  58. print($"Memory usage difference: {Format(finalTotalMemory - initialTotalMemory)} / {Format(Process.GetCurrentProcess().PrivateMemorySize64)}");
  59. }
  60. private string Format(long usage)
  61. {
  62. if (usage < 0)
  63. return $"-{Format(0 - usage)}";
  64. if (usage <= 1024 && usage >= 0)
  65. return $"{usage} Bytes";
  66. else if (usage > 1024 && usage <= 1024 * 1024)
  67. return $"{usage / 1024} KB";
  68. else
  69. return $"{usage / 1024 / 1024} MB";
  70. }
  71. }
  72. }