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.3 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using System;
  2. using System.Diagnostics;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using NumSharp;
  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. TensorShape shape = (1, 32, 32, 3);
  15. np.arange(shape.size).astype(np.float32).reshape(shape.dims);
  16. print($"tensorflow native version: v{tf.VERSION}");
  17. tf.Context.ensure_initialized();
  18. var a = tf.constant(np.ones(10, 10));
  19. var b = tf.Variable(a);
  20. var c = tf.Variable(b);
  21. var d = b * c;
  22. print(d.numpy());
  23. GC.Collect();
  24. GC.WaitForPendingFinalizers();
  25. }
  26. public void Execute(int epoch, int iterate, Action<int, int> process)
  27. {
  28. GC.Collect();
  29. GC.WaitForPendingFinalizers();
  30. var initialTotalMemory = Process.GetCurrentProcess().PrivateMemorySize64;
  31. print($"{process.Method.Name} started...");
  32. for (int i = 0; i < epoch; i++)
  33. {
  34. var initialMemory = Process.GetCurrentProcess().PrivateMemorySize64;
  35. for (int j = 0; j < iterate; j++)
  36. process(i, j);
  37. keras.backend.clear_session();
  38. GC.Collect();
  39. GC.WaitForPendingFinalizers();
  40. var finalMemory = Process.GetCurrentProcess().PrivateMemorySize64;
  41. print($"Epoch {i}: {Format(finalMemory - initialMemory)}.");
  42. }
  43. var finalTotalMemory = Process.GetCurrentProcess().PrivateMemorySize64;
  44. print($"Memory usage difference: {Format(finalTotalMemory - initialTotalMemory)} / {Format(Process.GetCurrentProcess().PrivateMemorySize64)}");
  45. }
  46. private string Format(long usage)
  47. {
  48. if (usage < 0)
  49. return $"-{Format(0 - usage)}";
  50. if (usage <= 1024 && usage >= 0)
  51. return $"{usage} Bytes";
  52. else if (usage > 1024 && usage <= 1024 * 1024)
  53. return $"{usage / 1024} KB";
  54. else
  55. return $"{usage / 1024 / 1024} MB";
  56. }
  57. }
  58. }