golang 併發遍歷指定目錄下的所有檔案大小

2021-08-21 05:24:03 字數 2186 閱讀 8295

這篇博文旨在寫乙個遍歷指定目錄下的所有檔案大小的demo,最後列印出該目錄所佔的空間大小,還會拿沒有使用goroutine的情況下, 計算所花費的時間。

先上乙個沒有使用goroutine的版本

package main

import (

"sync"

"time"

"fmt"

"path/filepath"

"os"

"log"

"io/ioutil"

)const (

//gotest目錄

go_test_dir_path = "/users/haodawang/documents/tests"

)var waitgroup sync.waitgroup

var ch = make(chan

struct{},1)

/* * 計算整個目錄所佔磁碟大小

*/func dirents(path string) (os.fileinfo, bool)

return entries, true

}//遞迴計算目錄下所有檔案

func walkdir(path string, filesize chan

for _, e := range entries else

}}func main()()

t := time.now()

for size := range filesize

fmt.println("花費的時間為 " + time.since(t).string())

fmt.printf("該目錄大小為 %.1fgb\n檔案總數為 %d\n", float64(sizecount)/1e9, filecount)

從上面的執行結果來看, 在我的tests目錄下,有3.3gb的東西,然後執行時間有8s多。

接下來看乙個goroutine的版本

package main

import (

"sync"

"time"

"fmt"

"path/filepath"

"os"

"log"

"io/ioutil"

)const (

//gotest目錄

go_test_dir_path = "/users/haodawang/documents/tests"

)var waitgroup sync.waitgroup

var ch = make(chan

struct{},255)

/* * 計算整個目錄所佔磁碟大小

*/func dirents(path string) (os.fileinfo, bool)

return entries, true

}//遞迴計算目錄下所有檔案

func walkdir(path string, filesize chan

entries, ok := dirents(path)

if !ok

for _, e := range entries else

}}func main()()

t := time.now()

for size := range filesize

fmt.println("花費的時間為 " + time.since(t).string())

fmt.printf("該目錄大小為 %.1fgb\n檔案總數為 %d\n", float64(sizecount)/1e9, filecount)

從執行結果來看的話,花費了4s多,基本上的花費是上個版本的一半。

這裡為了限制併發量,避免too many open file這樣的錯誤,使用了乙個臨時的channel

var ch = make(chan

struct{},255)

ch 

entries, ok := dirents(path)

VC 遍歷指定目錄下的檔案

用於輸出指定目錄下的所有檔案的檔名,包括子目錄。版本1 用string處理,方便,容易理解.include include include using namespace std bool isroot string path void findinall string path else 找到的是...

VC 遍歷指定目錄下的檔案

用於輸出指定目錄下的所有檔案的檔名,包括子目錄。版本1 用string處理,方便,容易理解.include include include using namespacestd boolisroot stringpath voidfindinall stringpath else 找到的是檔案 wh...

c 指定目錄下的檔案遍歷

要實現指定目錄下檔案的遍歷需要執行一下的部分 第一步獲取當前路徑的名字 max path是在windows定義的所有的路徑名字不超過其,呼叫該函式會使得得到當前的目錄 include char buff max path getcurrentdirectory max path,buff 接下來我們...