2012-03-24 36 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 2012-03-24 23:35:19

+0

我想你不關心,因爲你的程序在信息後退出,但如果沒有,你就有內存泄漏。 – ShinTakezou 2012-03-24 23:46:46

+0

這只是一個片段,是的時間a.out顯示時間。 – Andna 2012-03-24 23:49:59

回答

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

它的工作原理,似乎我的編程只是運行得如此之短,以致值很小。 – Andna 2012-03-25 07:58:11

3

編譯器可能會優化掉for循環,因爲它們什麼都不做。嘗試增加一個volatile變量。

如果您只想知道時間,請嘗試運行time ./app,它會打印執行應用程序的cputime,掛鐘時間等。

+0

事情是,我需要在應用程序中執行這些措施,因爲時間需要在代碼中的不同點進行比較。 – Andna 2012-03-24 23:50:34

2

的代碼可以簡單地寫在開始一個volatile變量,把你的「工作」的功能(在一個單獨的文件),然後是「工作」和涉及volatile打印東西后讀取volatile

或者做一些簡單的計算,將一部分計算隱藏在函數中,或者使用函數返回。

您正在使用什麼平臺(操作系統&編譯器)?

我不知道你在哪個平臺上運行,但關於更高精度系統時鐘的stackoverflow有幾個有用的問題。 High precision timing in userspace in Linux有幾個有用的鏈接和參考。

Timing Methods in C++ Under Linux看起來很有用。