2012-03-24 7 views
3

:でも、時間私はCプログラムによって取得され、どのくらい見たいので、私が書いたCで測定するとLinux

#include<stdio.h> 
    #include<stdlib.h> 
    #include"memory.h" 
    #include"memory_debug.h" 
    #include<sys/times.h> 
    #include<unistd.h> 

    int (*deallocate_ptr)(memContainer *,void*); 

    void (*merge_ptr)(node *); 

    void* (*allocate_ptr)(memContainer *,unsigned long size); 

    memContainer* (*init_ptr)(unsigned long); 

    diagStruct* (*diagnose_ptr)(memContainer *); 

    void (*finalize_ptr)(memContainer *); 

    void (*printNode_ptr)(node *n); 

    void (*printContainer_ptr)(memContainer *c); 

    void info(memContainer *c) 
    { 
    struct tms *t; 
    t=malloc(sizeof(struct tms)); 
    times(t); 
    printf("user : %d\nsystem : %d\n %d",t->tms_utime,(int)t->tms_stime); 
    diagnose_ptr(c); 
    printf("\n"); 
    return ; 
    } 

を私は、この関数を呼び出すときに私は0ユーザ時間と0システム時刻を取得します私が書く場合:

for (i=0;i<100000;++i) 
    for (j=0;j<10;++j) 
    {} 
info(c); 

私は間違って何をしていますか?

+0

あなたが実行 '時間a.out'、しても、その表示回数? – Douglas

+0

私はあなたのプログラムが情報の後に出てから気にしないと思いますが、もしそうでなければ、メモリリークがあります。 – ShinTakezou

+0

これは単なるスニペットです。時間はa.outです。 – Andna

答えて

1

以下のデモプログラムの出力をゼロ以外回:

#include<stdio.h> 
#include<stdlib.h> 
#include"memory.h" 
#include<sys/times.h> 
#include<unistd.h> 
#include <iostream> 
using namespace std; 

int main() 
{ 
    int x = 0; 
    for (int i = 0; i < 1 << 30; i++) 
     x++; 

    struct tms t; 
    times(&t); 
    cout << t.tms_utime << endl; 
    cout << t.tms_stime << endl; 
    return x; 
} 

出力:あなたが期待

275 
1 
+0

それは動作します、私のprogはちょうどその値が非常に小さいので、短い実行されているようです。 – Andna

3

コンパイラはおそらく、何もしないので、forループを最適化します。変数volatileをインクリメントしてみてください。

時間を知りたい場合はtime ./appを実行してください。実行されたアプリケーションのcputime、wall clock timeなどが表示されます。

+0

ものだけです。 – Andna

2

コードは単純にし、「仕事」とvolatileを含む印刷何か後volatileを読んで、(別のファイルに)機能であなたの仕事」を入れて、起動時にvolatile変数を書くことができます。

関数に埋め込まれた計算の一部を使用して、または関数の戻り値を使用して簡単な計算を行うか、

どのプラットフォーム(オペレーティングシステム&コンパイラ)を使用していますか?

実行しているプラ​​ットフォームがわかりませんが、より高精度のシステムクロックについては、stackoverflowに関するいくつかの便利な質問があります。 High precision timing in userspace in Linuxにはいくつかの便利なリンクと参照があります。

Timing Methods in C++ Under Linuxと思われます。

関連する問題