我刚刚在Haskell中写了这一行,看看我每秒使用多少带宽:
>>> import Control.Monad (forever) >>> import Control.Concurrent (threadDelay) -- microseconds; 10^6μs = 1s >>> let f = "/sys/class/net/wlan0/statistics/rx_bytes" in forever $ readFile f >>= \a -> threadDelay (10^6) >> readFile f >>= \b -> print (read b - read a) 0 0 0 0 0 0 0 0 0但它总是说0.我在Bash中并行运行了一行代码,这表明在这段时间内文件确实在变化:
$ f=/sys/class/net/wlan0/statistics/rx_bytes; while true; do a=`cat $f`; sleep 1; echo $((`cat $f`-a)); done 98 98 2132 3178 230 306 98 98 729为什么Haskell没有看到它改变?
I just wrote this one liner in Haskell to see the how much bandwidth I'm using per second:
>>> import Control.Monad (forever) >>> import Control.Concurrent (threadDelay) -- microseconds; 10^6μs = 1s >>> let f = "/sys/class/net/wlan0/statistics/rx_bytes" in forever $ readFile f >>= \a -> threadDelay (10^6) >> readFile f >>= \b -> print (read b - read a) 0 0 0 0 0 0 0 0 0But it always says 0. I ran in parallel an equivalent line of code in Bash, which shows that the file was indeed changing during this time:
$ f=/sys/class/net/wlan0/statistics/rx_bytes; while true; do a=`cat $f`; sleep 1; echo $((`cat $f`-a)); done 98 98 2132 3178 230 306 98 98 729Why does Haskell not see it changing?
最满意答案
readFile是懒惰的,也就是说,除非你计算绑定的变量,否则它实际上并不访问文件中的数据:在你的情况下, read a 。 此时线程延迟已经通过,并且您评估的文件处于与b相同的状态!
这样做:
forever $ do a <- fmap read $ readFile f a `seq` threadDelay (10^6) b <- fmap read $ readFile f print $ b - areadFile is lazy, i.e. it doesn't actually access the data in the file until you evaluate the variable bound to it: in your case, read a. At which time the thread delay has already passed, and you evaluate the file in the same state as b!
Do it this way:
forever $ do a <- fmap read $ readFile f a `seq` threadDelay (10^6) b <- fmap read $ readFile f print $ b - a更多推荐
发布评论