diff --git a/cmd/ipfs/ipfs.go b/cmd/ipfs/ipfs.go
index 57b48c33fa5d21491e787ac1956736d06b4a953f..1494f68c221c3fb0b3ad76f4693b65c19ca306db 100644
--- a/cmd/ipfs/ipfs.go
+++ b/cmd/ipfs/ipfs.go
@@ -17,6 +17,8 @@ import (
 	u "github.com/jbenet/go-ipfs/util"
 )
 
+const heapProfile = "ipfs.mprof"
+
 // The IPFS command tree. It is an instance of `commander.Command`.
 var CmdIpfs = &commander.Command{
 	UsageLine: "ipfs [<flags>] <command> [<args>]",
@@ -117,6 +119,13 @@ func main() {
 		}
 		os.Exit(1)
 	}
+
+	if u.Debug {
+		err := writeHeapProfileToFile()
+		if err != nil {
+			log.Critical(err)
+		}
+	}
 	return
 }
 
@@ -220,3 +229,12 @@ func setupDaemon(confdir string, node *core.IpfsNode) (*daemon.DaemonListener, e
 	go dl.Listen()
 	return dl, nil
 }
+
+func writeHeapProfileToFile() error {
+	mprof, err := os.Create(heapProfile)
+	if err != nil {
+		log.Fatal(err)
+	}
+	defer mprof.Close()
+	return pprof.WriteHeapProfile(mprof)
+}